Solution purely based on if statement


  • 1
    L

    wrote a code using nothing but 3 constant and lots of if statement

    public class Solution {
        public boolean isValid(String s) {
            int count1 = 0,count2 = 0,count3 = 0;
            for(int i=0;i<s.length();i++){
            
            	if('('==s.charAt(i)) count1++;
                else if('{'==s.charAt(i)) count2++;
                else if('['==s.charAt(i)) count3++;
                else if(')'==s.charAt(i)) count1--;
                else if('}'==s.charAt(i)) count2--;
                else if(']'==s.charAt(i)) count3--;
                
                if(count1<0||count2<0||count3<0) return false;
                else if(')'==s.charAt(i)){
                	if('['==s.charAt(i-1)||'{'==s.charAt(i-1)) return false;}
                else if('}'==s.charAt(i)){
                	if('['==s.charAt(i-1)||'('==s.charAt(i-1)) return false;}
                else if(']'==s.charAt(i)){ 
                	if('('==s.charAt(i-1)||'{'==s.charAt(i-1)) return false;}
                
            }
            if(count1==0&&count2==0&&count3==0)
            return true;
            else
            return false;
        }
    }

  • 4
    W

    Your code would return true on this input:

    [([]])
    

  • 0
    L

    you're right, I somehow managed to pass the OJ test, but the code is still wrong, should remind them to complete their test cases


  • 0
    S

    hi @weird, thanks a lot. We have added this test case. @leon.fee, sorry about that the solution should get wrong answer now. :P


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.