题目:
给定一个只包括 '(',')','{','}','[',']'
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
示例 1:
输入:s = "()"
输出:true
示例 2:
输入:s = "()[]{}"
输出:true
示例 3:
输入:s = "(]"
输出:false
示例 4:
输入:s = "([)]"
输出:false
示例 5:
输入:s = "{[]}"
输出:true
提示:
1 <= s.length <= 104
s 仅由括号 '()[]{}' 组成
参考题解答案:
package leetCode;
import java.util.Stack;
public class JudgeKuoHu {
public static void main(String[] args) {
String str = "{[()]}";
JudgeKuoHu judgeKuoHu = new JudgeKuoHu();
boolean solution = judgeKuoHu.solution(str);
System.out.println(solution);
}
public boolean solution(String str){
Stack stack = new Stack<>();
for (int i = 0; i < str.length(); i++){
char s = str.charAt(i);
if (s == '(' || s == '[' || s == '{'){
stack.push(s);
}
else{
if (stack.empty() == true) return false;
Character pop = stack.pop();
if (s == ')' && pop != '(') return false;
if (s == ']' && pop != '[') return false;
if (s == '}' && pop != '{') return false;
}
}
if (stack.empty() == true) return true;
else return false;
}
}
结果输出:



