- Valid Parentheses
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 左括號時入棧相關info,右括號時使出棧檢查配對
思路:
遇到'(', '[', '{' 時將所需配對的右括號 入棧,其他字符時與出棧字符看是否相等(驗證是否因為上一個未匹配的左括號所需)
Time Complexity: O(n)
Space Complexity: O(n)
Solution Code:
public class Solution {
public boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<Character>();
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == '(') stack.push(')');
else if(c == '[') stack.push(']');
else if(c == '{') stack.push('}');
else if (stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
}
}