DEV Community

Takahiro Kudo
Takahiro Kudo

Posted on

2 2

LeetCode "Valid Parentheses"

I'm often confused by the index of counter🙄

Valid Parentheses

class Solution:
    def isValid(self, s: str) -> bool:

        len_s = len(s)

        if len_s == 0:
            return True
        elif len_s < 2:
            return False

        close_parentheses = {'(': ')', '{': '}', '[': ']'}

        # @note: it's faster to start with i = 1, but i = 0 and check i + 1 is easier to understand.
        i = 0
        while (i + 1) < len_s:
            c = s[i]
            if (c == '(' or c == '{' or c == '[') and s[i + 1] == close_parentheses[c]:
                len_s -= 2
                if 0 < len_s:
                    s = s[0:i] + s[i + 2:]
                    i -= 1                    
                continue                
            i += 1

        return len_s == 0



Enter fullscreen mode Exit fullscreen mode

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay