Leetcode: Valid Parentheses

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

bool isValid(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int len = s.length();
    	if(len==0) return true;
		if(len%2) return false;
		for(int i = 1; i < len; i++)
			if(s[i-1] == '{' && s[i]=='}')
			{
				string ss = s.substr(0, i-1) + s.substr(i+1);
				return isValid(ss);
			}
			else if(s[i-1] == '[' && s[i]==']')
			{
				string ss = s.substr(0, i-1) + s.substr(i+1);
				return isValid(ss);
			}
			else if(s[i-1] == '(' && s[i]==')')
			{
				string ss = s.substr(0, i-1) + s.substr(i+1);
				return isValid(ss);
			}
		return false;
    }




bool isValid(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int len = s.length();
    	if(len==0) return true;
		if(len%2) return false;
		stack<char> sk;
		for(int i = 0; i < len; i++)
		{
			if(s[i] == '(') sk.push(')');
			else if(s[i] == '{') sk.push('}');
			else if(s[i] == '[') sk.push(']');
			else if(sk.empty() || sk.top() != s[i]) return false;
			else sk.pop();
		}
		return sk.empty();
    }



你可能感兴趣的:(LeetCode,valid,Parentheses)