LeetCode 20. Valid Parentheses
Woodyiiiiiii opened this issue · comments
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
题目要求匹配括号,很简单。C++解法如下:
class Solution {
public:
bool isValid(string s) {
stack<char> help;
for (int i = 0; i < s.size(); ++i) {
char c = s[i];
if (c == '(' || c == '[' || c == '{')
help.push(c);
else {
if (help.empty()) return false;
char old = help.top();
help.pop();
if (c == ')' && old != '(')
return false;
else if (c == ']' && old != '[')
return false;
else if (c == '}' && old != '{')
return false;
}
}
if (!help.empty()) return false;
else return true;
}
};
Java的栈(容器)是不能存储基本类型的,只能做一个标记:
class Solution {
public boolean isValid(String s) {
if (s.isEmpty()) {
return true;
}
Stack<Integer> help = new Stack();
int i = 0;
for (; i < s.length(); ++i) {
if (s.charAt(i) == '(')
help.push(1);
else if (s.charAt(i) == '[')
help.push(2);
else if (s.charAt(i) == '{')
help.push(3);
else {
char now = s.charAt(i);
if (help.empty())
return false;
int old = help.pop();
if (now == ')' && old != 1)
return false;
else if (now == ']' && old != 2)
return false;
else if (now == '}' && old != 3)
return false;
}
}
if (help.empty())
return true;
else
return false;
}
}
参考资料:
LeetCode原题