Come from : [https://leetcode-cn.com/problems/valid-parentheses/]
20. Valid Parentheses
1.Question
Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1 :
Input: "()"
Output: true
Example 2 :
Input: "()[]{}"
Output: true
Example 3 :
Input: "(]"
Output: false
Example 4 :
Input: "([)]"
Output: false
Example 5 :
Input: "{[]}"
Output: true
2.Answer
easy类型题目。。
我的方法:(利用栈数据结构)
利用栈的性质,先进后出,遇到左括号则压入栈,遇到右括号则与栈顶元素匹配,若匹配成功则将栈顶元素弹出,反之返回false。
AC代码如下:
class Solution {
public:
bool isValid(string s) {
stack<char> s_stack;
for(int i = 0; i < s.size(); ++i)
{
if(s[i] == ']')
{
if(s_stack.size() == 0 || s_stack.top() != '[' ) return false;
else s_stack.pop();
}
else if(s[i] == '}')
{
if(s_stack.size() == 0 || s_stack.top() != '{' ) return false;
else s_stack.pop();
}
else if(s[i] == ')')
{
if(s_stack.size() == 0 || s_stack.top() != '(' ) return false;
else s_stack.pop();
}
else
{
s_stack.push(s[i]);
}
}
if (s_stack.size() == 0) return true;
else return false;
}
};
3.大神解答
速度排名第一(哈希表)。
class Solution {
public:
bool isValid(string s) {
if(s.length()%2!=0) return false;//一但是奇数说明不是有效的括号
map<char,char> wordbook;//建立哈希表
wordbook.insert(map<char,char>::value_type(')','('));
wordbook.insert(map<char,char>::value_type(']','['));
wordbook.insert(map<char,char>::value_type('}','{'));
stack<char> mystack;//建立栈
for(int i=0;i<s.length();i++)
{
if(s[i]=='['||s[i]=='{'||s[i]=='(')//匹配到左括号
mystack.push(s[i]);//放入栈中
else if(s[i]==']'||s[i]=='}'||s[i]==')')//匹配到右括号
{
if(mystack.empty()) return false;
//匹配到右括号,栈中应该存在左括号。否则就是无效的括号
if(wordbook[s[i]]==mystack.top())//与栈顶元素进行匹配
{
mystack.pop();//匹配成功删除栈顶元素
continue;
}
else return false;
}
}
if(mystack.empty()) return true;//有效的括号到最后检测结束栈中应没有元素
else return false;
}
};
4.我的收获
fighting。。。
2019/7/3 胡云层 于南京 113