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.
用一个stack,如果是括号左边push,右边就和pop出来的比较是否为一对(检查stack是否已经为空)。最后检查遍历完后,stack是否为空。
public class Solution {
//Time: O(n)
public boolean isValid(String s) {
if (s == null || s.length() == 0) {
return false;
}
HashMap<Character, Character> map = new HashMap<Character, Character>();
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
if (map.containsKey(s.charAt(i))) {
stack.push(s.charAt(i));
} else {
if (stack.isEmpty() || map.get(stack.peek()) != s.charAt(i)) {
return false;
}
stack.pop();
}
}
if (!stack.isEmpty()) {
return false;
}
return true;
}
}
No comments:
Post a Comment