Main idea: each time find ch == ‘c’ check top of stack of they are ‘a’,’b’ in order, then pop them off time O(N) space O(N)
class Solution:
def isValid(self, s: str) -> bool:
# checki if s is potential candidate
counter = collections.Counter(s)
if len(set(counter.values())) != 1:
return False
if s[0] != 'a':
return False
st = []
i = 0
n = len(s)
while i < n:
if s[i] == 'c' :
if len(st) >= 2 and st[-1] == 'b' and st[-2] == 'a':
st.pop()
st.pop()
i += 1
continue
st.append(s[i])
i += 1
return True if len(st) == 0 else False
faster solution
class Solution:
def isValid(self, S):
S2 = ""
while S != S2:
S, S2 = S.replace("abc", ""), S
return S == ""