LeetCode20. 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.
思路
这题我是直接看的网上的题解,感觉该博主第二种思路非常好,简单描述一下。
就是遍历输入的字符串中的字符,如果遇到’(‘就将’)’push入栈,遇到’[‘就将’]’push入栈,遇到’{‘就将’}’push入栈;如果栈为空或者字符串当前字符不等于栈顶元素就说明该字符串不满足条件,如果当前字符串中的字符和栈顶字符相同,就将栈顶元素pop出;最后看栈是不是为空。
代码实现
class Solution {
public:
bool isValid(string s) {
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();
}
};
鸡汤
好几天没写博客了,感觉最近状态不是很好,及时调整,继续坚持!