Description

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'

Constraints:

  • 1 <= s.length <= 1000
  • s[i] = ‘L’ or ‘R’

分析

题目的意思是:把一个字符串分割为相等的字符串,即L的数量和R的数量相等,返回最大的分割数。思路也很直接,遍历,L_cnt记录的是L的数目,R_cnt记录的是R的数目,当L_cnt==R_cnt,说明可以分割成一个平衡字符串了,res加1,这样遍历下去,返回最终的res就行了。

代码

class Solution:
def balancedStringSplit(self, s: str) -> int:
L_cnt=0
R_cnt=0
res=0
for ch in s:
if(ch=='L'):
L_cnt+=1
elif(ch=='R'):
R_cnt+=1
if(L_cnt==R_cnt):
res+=1
return res