Java solution with custom stack


  • 0
    L

    Maybe extensibility is better.

    public class Solution {
        public boolean isValid(String s) {
            char[] ch = {'(', '{', '[', ']', '}',')'};
            char[] stack = new char[s.length()];
            int k = 0;//top sign
            HashMap<Character,Integer> map = new HashMap<Character,Integer>();
            for(int i=0; i<ch.length; i++){
                map.put(ch[i],i);
            }
            for(int i=0; i<s.length(); i++){
                int temp = map.get(s.charAt(i));
                if(temp<ch.length/2)
                    stack[k++] = ch[temp];
                else{
                    if(k==0) return false;
                    if(stack[--k] != ch[ch.length-1-temp])
                        return false;
                }
            }
            return k==0?true:false;
        }
    }

Log in to reply
 

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