Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I had a question regarding leetcode problem number 20, "Valid Parenthesis"

I have been trying to do this question by myself, right now I all over the place when it comes to trying to figure out my level of python. So I recently started trying the exercises and I attempted this exercise just by the top of my head, but when I run the program in Pycharm and replit it gives me the right answers however when I run it in leetcode the program does not pass the tests and in fact gives me the opposite answers. Whoever can help me figure out why I would greatly appreciate it.
And if possible also tell me some recommendation about where to aim to go in python and what language to establish after it.

Thank you 🙂

This is the code that I have tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Solution:
  def isValid(self, s: str) -> bool:
    s2=sorted(s)
    s1 = str(s2)[1:-1]
    count = 0
    extcount=0
    for i in range (len(s1)):
        if s1[i] == '(':
            count += 1.3
        elif s1[i] == '[':
            count += 2.7
        elif s1[i]=='{':
            count += 3.1
        elif s1[i] == ')':
            count -= 1.3
        elif s1[i] == ']':
            count -= 2.7
        elif s1[i]== '}':
            count -= 3.1
        else:
            pass
    if count==0:
        extcount+=1
        x=bool(extcount)
        print(x)
    else: 
        print (bool(extcount))

Sorry for the code being so primitive.

>Solution :

Your approach to solving Valid Parentheses won’t work because sorting the string breaks the original order, making it impossible to validate balanced parentheses.

Consider the string s = "([)]". This string is not a set of valid parentheses, but let’s see what happens when you sort it.

Sorted s: s2 = "()[]"

Your count-based method would incorrectly identify this as balanced because you have one of each type of parenthesis, and your count would end up being zero. However, the original string s was not balanced due to the ordering: the brackets don’t close in the last-in, first-out (LIFO) order.

So, sorting breaks the spatial relationship needed to validate the sequence, making it an incorrect approach for this problem.


Instead try using a Stack to solve this problem:

class Solution:
    def isValid(self, s: str) -> bool:
        closing_by_opening = {'(': ')', '{': '}', '[': ']'}
        stack = []
        for c in s:
            if c in closing_by_opening:
                stack.append(c)
            else:
                if not stack or closing_by_opening[stack.pop()] != c:
                    return False
        return not stack
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading