描述
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"
Output: 4
Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.
Example 2:
Input: s = "RLLLLRRRLR"
Output: 3
Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'.
Example 3:
Input: s = "LLLLRRRR"
Output: 1
Explanation: s can be split into "LLLLRRRR".
Example 4:
Input: s = "RLRRRLLRLL"
Output: 2
Explanation: s can be split into "RL", "RRRLLRLL", since each substring contains an equal number of 'L' and 'R'
Note:
1 <= s.length <= 1000
s[i] = 'L' or 'R'
解析
根据题意,要找出 s 中包含了多少个 Balanced string ,那么只要遍历字符串 s ,用计数器遇到 L 加一,遇到 R 减一,当计数器为 0 的时候,将平衡字符串数量 n 加一,遍历结束之后即可得出 s 可以分割多少个平衡字符串。
解答
class Solution(object):
def balancedStringSplit(self, s):
"""
:type s: str
:rtype: int
"""
count = 0
n = 0
for c in s:
if c =='L':
count+=1
elif c== 'R':
count-=1
if count == 0:
n+=1
return n
运行结果
Runtime: 12 ms, faster than 96.02% of Python online submissions for Split a String in Balanced Strings.
Memory Usage: 13.4 MB, less than 86.98% of Python online submissions for Split a String in Balanced Strings.