0ms java solution not use stack


  • -2
    S
    public class Solution {
        public boolean isValid(String s) {
            if(s.length()%2!=0)return false;
            char[] b=new char[]{'(',')','{','}','[',']'};
            char[] stack=new char[s.length()];
            char[] source=s.toCharArray();
            if(!(source[0]==b[0]||source[0]==b[2]||source[0]==b[4]))return false;
            int point=0;
            for(int i=0;i<s.length();i++){
                if(source[i]==b[0]||source[i]==b[2]||source[i]==b[4]){
                    stack[point++]=source[i];
                }
                else if(source[i]==b[1]&&stack[point-1]==b[0]){
                    point--;
                }
                 else if(source[i]==b[3]&&stack[point-1]==b[2]){
                    point--;
                }
                 else if(source[i]==b[5]&&stack[point-1]==b[4]){
                    point--;
                }
                else
                    return false;
                    
                if(point<0) return false;
            }
            if(point==0)
            return true;
            
            return false;
        }
    }

  • 0
    T

    Aaah, I was expecting an O(1) solution, you're still using a stack, you even called it that. What you're not using is Java's builting Stack collection or Deque interface. Please modify the title.


  • 0
    T

    I think you'll get better performance and readabilty if you inline the b array everywhere.


Log in to reply
 

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