LeetCode 0020 Valid Parentheses
作者:互联网
1. 题目描述
2. Solution 1
1、思路分析
遇到左括号认为优先级低,入栈;遇到右括号,若栈空,不匹配,若栈顶元素不是对应的括号,不匹配,不然弹栈,继续遍历;遍历完,栈不空,不匹配。
2、代码实现
package Q0099.Q0020ValidParentheses;
import java.util.ArrayDeque;
import java.util.Deque;
public class Solution1 {
public boolean isValid(String s) {
Deque<Character> brackets = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '[' || c == '{') brackets.push(c);
else if (c == ')') {
if (brackets.isEmpty()) return false;
else if (brackets.peek() == '(') brackets.pop();
else return false;
} else if (c == ']') {
if (brackets.isEmpty()) return false;
else if (brackets.peek() == '[') brackets.pop();
else return false;
} else if (c == '}') {
if (brackets.isEmpty()) return false;
else if (brackets.peek() == '{') brackets.pop();
else return false;
}
}
return brackets.isEmpty();
}
}
3. Solution 2
1、思路分析
使用Map保存匹配的括号,简化代码。
2、代码实现
package Q0099.Q0020ValidParentheses;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;
public class Solution2 {
public boolean isValid(String s) {
Deque<Character> brackets = new ArrayDeque<>();
Map<Character, Character> bracketMaps = new HashMap<>();
bracketMaps.put(')', '(');
bracketMaps.put(']', '[');
bracketMaps.put('}', '{');
for (char c : s.toCharArray()) {
if (bracketMaps.containsValue(c)) brackets.push(c); // 左括号 => 进栈
else if (brackets.isEmpty() || bracketMaps.get(c) != brackets.pop()) return false;
}
return brackets.isEmpty();
}
}
4. Solution 3
1、思路分析
遇到左括号,对应的右括号入栈;遇到右括号,栈空或栈顶元素与当前遍历元素不相等,说明不匹配。
2、代码实现
package Q0099.Q0020ValidParentheses;
import java.util.ArrayDeque;
import java.util.Deque;
public class Solution3 {
public boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
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();
}
}
标签:0020,return,brackets,else,Valid,isEmpty,import,false,LeetCode 来源: https://www.cnblogs.com/junstat/p/15983399.html