一.问题描述
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".
Constraints:
1 <= s.length <= 1000
s[i] = 'L' or 'R'
二.解决思路
要将原序列分割成多个子平衡序列。
顺序遍历,一边遍历一边保存出现的r和l的次数,并判断r和l次数是否相同,相同的话则是一个平衡序列,然后清空计数器进行下一次计算,因为是分割序列,所以必然平衡子序列是一个接着一个的。
为了减少一次if语句的判断,我将l和r与索引map。
同时发现一个用库函数一行代码解决的方法。也放在源码部分了。
更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我
欢迎大家一起套路一起刷题一起ac
三.源码
class Solution:
def balancedStringSplit(self, s: str) -> int:
cnt=[0,0]
ch_to_num={'L':0,'R':1}
rst=0
for ch in s:
cnt[ch_to_num[ch]]+=1
if cnt[ch_to_num[ch]]==cnt[ch_to_num[ch]-1]:
rst+=1
cnt[ch_to_num[ch]],cnt[ch_to_num[ch]-1]=0,0
return rst
一行代码解决:作者:https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/403975/Python3-1-liner
from itertools import accumulate as acc
class Solution:
def balancedStringSplit(self, s: str) -> int:
return list(acc(1 if c == 'L' else -1 for c in s)).count(0)
关于accumulate函数在我上一篇博客有讲。