在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Balanced strings are those who have equal quantity of 'L' and 'R' characters. Given a balanced string s split it in the maximum amount of balanced strings. Return the maximum amount of splitted balanced strings. Example 1: Input: s = "RLRRLLRLRL" Input: s = "RLLLLRRRLR" Input: s = "LLLLRRRR" Constraints: 1 <= s.length <= 1000 在一个「平衡字符串」中,'L' 和 'R' 字符的数量是相同的。 给出一个平衡字符串 s,请你将它分割成尽可能多的平衡字符串。 返回可以通过分割得到的平衡字符串的最大数量。 示例 1: 输入:s = "RLRRLLRLRL" 输入:s = "RLLLLRRRLR" 输入:s = "LLLLRRRR" 提示: 1 <= s.length <= 1000 0ms 1 class Solution { 2 func balancedStringSplit(_ s: String) -> Int { 3 if s.isEmpty { return 0 } 4 5 var r = 0 6 var l = 0 7 var count = 0 8 var arrayString = Array(s) 9 for var i in 0..<arrayString.count { 10 if arrayString[i] == "L" { 11 l += 1 12 } else { 13 r += 1 14 } 15 16 if r == l { 17 count += 1 18 } 19 } 20 return count 21 } 22 } 4ms 1 class Solution { 2 func balancedStringSplit(_ s: String) -> Int { 3 var balance = 0 4 var count = 0 5 6 for cha in s { 7 if cha == "R" { 8 balance += 1 9 } else { 10 balance -= 1 11 } 12 13 if balance == 0 { 14 count += 1 15 } 16 } 17 18 return count 19 } 20 } 8ms 1 class Solution { 2 func balancedStringSplit(_ s: String) -> Int { 3 var b = 0 4 var ans = 0 5 for c in s { 6 if c == "L" { 7 b -= 1 8 } else { 9 b += 1 10 } 11 if b == 0 { 12 ans += 1 13 } 14 } 15 return ans 16 } 17 } 12ms 1 class Solution { 2 func balancedStringSplit(_ s: String) -> Int { 3 var counter = 0 4 var balancedStrings = [String]() 5 var balancedString = "" 6 for char in s { 7 var val = char == "R" ? 1 : -1 8 counter += val 9 10 if counter == 0 { 11 balancedStrings.append(balancedString) 12 balancedString = "" 13 } else { 14 balancedString += String(char) 15 } 16 } 17 return balancedStrings.count 18 } 19 }
|
请发表评论