隔了超级长时间又开始更新。。
还是找地方存代码
最近在刷leetcode,主要觉得自己编程水平严重不足
这个也不会记录所有的刷过的题啦
主要是记录一下我觉得有意思比较重要的
题目描述
1221. Split a String in Balanced Strings
Easy
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:
Input: s = "RLRRLLRLRL" Output: 4 Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.
Input: s = "RLLLLRRRLR" Output: 3 Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'.
Input: s = "RLRRRLLRLL" Output: 2 Explanation: s can be split into "RL", "RRRLLRLL", since each substring contains an equal number of 'L' and 'R'
class Solution:
def balancedStringSplit(self, s: str) -> int:
Lnums = 0 #The number of L staying in the stack
Rnums = 0 #The number of S staying in the stack
numOfstr = 0
stack = []
for i in range(len(s)):
if len(stack) == 0:
if s[i] == 'L':
Lnums += 1
else:
Rnums += 1
stack.append(s[i])
elif (len(stack) != 0):
if s[i] == 'L':
Lnums += 1
else:
Rnums += 1
stack.append(s[i])
if Lnums == Rnums:
string = stack[0:-1]
numOfstr += 1
stack = []
else:
continue
return numOfstr
大概思想就是建一个栈,不停入栈出栈,每次都判断栈内元素是否平衡,平衡了就前面的都出栈,清空栈。
比较像括号配对,但是括号配对比这个难