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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

đź‘‹ Kindness is contagious

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

Okay