1221. Split a String in Balanced Strings - LeetCode Solution


String Greedy Counting

Python Code:

class Solution:
    def balancedStringSplit(self, s: str) -> int:
        count = -1
        stack = []
        
        for i in range(len(s)):
            if not stack:
                count+=1
                stack.append(s[i])
            else:
                if stack[-1] != s[i]:
                    stack.pop()
                else:
                    stack.append(s[i])
        if not stack:
            count+=1
        return count


Comments

Submit
0 Comments
More Questions

25A - IQ test
785A - Anton and Polyhedrons
1542B - Plus and Multiply
306A - Candies
1651C - Fault-tolerant Network
870A - Search for Pretty Integers
1174A - Ehab Fails to Be Thanos
1169A - Circle Metro
780C - Andryusha and Colored Balloons
1153A - Serval and Bus
1487C - Minimum Ties
1136A - Nastya Is Reading a Book
1353B - Two Arrays And Swaps
1490E - Accidental Victory
1335A - Candies and Two Sisters
96B - Lucky Numbers (easy)
1151B - Dima and a Bad XOR
1435B - A New Technique
1633A - Div 7
268A - Games
1062B - Math
1294C - Product of Three Numbers
749A - Bachgold Problem
1486B - Eastern Exhibition
1363A - Odd Selection
131B - Opposites Attract
490C - Hacking Cypher
158B - Taxi
41C - Email address
1373D - Maximum Sum on Even Positions