Stack
String
Description:
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.
堆栈的典型例子
my Solution:
public class Solution {
public boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
if (s.length() == 0)
return true;
else {
for (int i = 0; i < s.length(); i++) {
Character ch = s.charAt(i);
if (!stack.isEmpty()) {
Character temp = stack.peek();
if ((temp == '(' && ch == ')') || (temp == '[' && ch == ']') || (temp == '{' && ch == '}')) {
stack.pop();
} else {
stack.push(ch);
}
} else {
stack.push(ch);
}
}
}
return stack.isEmpty();
}
}