[leetcode] 1221. Split a String in Balanced Strings

网友投稿 734 2022-10-01

[leetcode] 1221. Split a String in Balanced Strings

[leetcode] 1221. Split a String in Balanced Strings

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: 4Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.

Example 2:

Input: s = "RLLLLRRRLR"Output: 3Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'.

Example 3:

Input: s = "LLLLRRRR"Output: 1Explanation: s can be split into "LLLLRRRR".

Example 4:

Input: s = "RLRRRLLRLL"Output: 2Explanation: s can be split into "RL", "RRRLLRLL", since each substring contains an equal number of 'L' and 'R'

Constraints:

1 <= s.length <= 1000s[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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:微信小程序页面开发(微信小程序页面开发教程)
下一篇:小程序中解决代码同步执行的问题(小程序错误代码)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~