[LeetCode]20.有效的括号(Java)
原题地址: valid-parentheses
题目描述:
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
示例 1:
输入:s = "()"
输出:true
示例 2:
输入:s = "()[]{}"
输出:true
示例 3:
输入:s = "(]"
输出:false
示例 4:
输入:s = "([)]"
输出:false
示例 5:
输入:s = "{[]}"
输出:true
提示:
1 <= s.length <= 104
s 仅由括号 '()[]{}' 组成
解答方法:
1.
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
boolean result = false;
for(int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') {
stack.push(s.charAt(i));
} else {
if(!stack.isEmpty()) {
switch (s.charAt(i)) {
case ')':
if (stack.peek() == '(') stack.pop();
else return result;
break;
case ']':
if (stack.peek() == '[') stack.pop();
else return result;
break;
case '}':
if (stack.peek() == '{') stack.pop();
else return result;
break;
}
}else return result;
}
}
if(stack.isEmpty())result = true;
return result;
}
}
2.评论中解法
class Solution {
public boolean isValid(String s) {
Stack<Character>stack = new Stack<Character>();
for(char c: s.toCharArray()){
if(c=='(')stack.push(')');
else if(c=='[')stack.push(']');
else if(c=='{')stack.push('}');
else if(stack.isEmpty()||c!=stack.pop())return false;
}
return stack.isEmpty();
}
}
class Solution {
public boolean isValid(String s) {
int length = s.length() / 2;
for (int i = 0; i < length; i++) {
s = s.replace("()", "").replace("{}", "").replace("[]", "");
}
return s.length() == 0;
}
}