Use ascii code to make it simple


  • 0
    O

    the ASCII code of (){}[] are: 40 41 123 125 91 93

    class Solution {
    public:
        bool isValid(string s) {
            stack<char> st;
            int i=0;
            while(s[i]!='\0')
            {
                if(s[i]=='('||s[i]=='{'||s[i]=='[')
                   {
                       st.push(s[i]);
                       i++;
                   }
                else{
                    if(!st.empty()&&(s[i]-1==st.top()||s[i]-2==st.top()))
                    {
                        st.pop();
                        i++;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            return st.empty();
        }
    };

  • 0
    Z

    The ASCII code of (){}[] are: 40 41 123 125 91 93, so the code just to compare the ascii value.

    Add a dummy value to stack first, to simplify the code using stack.peek().

        public boolean isValid(String s) {
            Stack<Integer> stack = new Stack<Integer>();
            stack.push(0);
            for (int i = 0; i < s.length(); i++) {
                int c = s.charAt(i);
                if (stack.peek() + 1 == c || stack.peek() + 2 == c)
                    stack.pop();
                else
                    stack.push(c);
            }
            return stack.size() == 1;
        }

Log in to reply
 

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