Share my AC C++ code (2ms) and some mistakes I made


  • 1
    Y
    class Solution {
    public:
        bool isValid(string s) {
            stack<char> left;
    		for(int i=0;i<s.length();i++)
    		{
    			char ch=s[i];
    			if(ch=='('||ch=='['||ch=='{')
    			{
    				left.push(ch);
    				continue;
    			}
    			//else ch==),],}
    			if(left.empty())
    				return false;
    			//now left!=empty ch = ) ] }
    			if(ch-left.top()<=2)//match via ascii
    				left.pop();//here cause WA,else means nomatch must return false
    			else
    				return false;
    		}
    		return left.empty();
        }
    };

  • 0
    X

    a similar one:

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

Log in to reply
 

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