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.
Subscribe to see which companies asked this question
借助棧來實現:
如果為左括號則入棧; 如果為右括號, 若:stack.empty()
。
C++:
// Runtime: 0 ms
class Solution {
public:
bool isValid(string s) {
unordered_map mymap = {{'(', ')'}, {'[', ']'}, {'{', '}'}};
stack mystack;
for (int i = 0; i < s.length(); i++)
{
if (s[i] == '(' || s[i] == '[' || s[i] == '{')
{
mystack.push(s[i]);
}
else if (!mystack.empty() && (mymap[mystack.top()] == s[i]))
{
mystack.pop();
}
else
{
return false;
}
}
return mystack.empty();
}
};
Java:
// Runtime: 2 ms
public class Solution {
public boolean isValid(String s) {
Map map = new HashMap();
Stack stack = new Stack();
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');
for (int i = 0; i < s.length(); i++) {
if (map.containsKey(s.charAt(i))) {
stack.push(s.charAt(i));
}
else if (!stack.empty() && map.get(stack.peek()).equals(s.charAt(i))) {
stack.pop();
}
else {
return false;
}
}
return stack.empty();
}
}