每日一题
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。左括号必须以正确的顺序闭合。
示例 1:
输入:s = "()"输出:true
示例 2:
输入:s = "()[]{}"输出:true
示例 3:
输入:s = "(]"输出:false
示例 4:
输入:s = "([)]"输出:false
示例 5:
输入:s = "{[]}"输出:true
提示:
1 <= s.length <= 104s 仅由括号 '()[]{}' 组成
解答:使用栈
public class Day5 {
public static void main(String[] args) {
// boolean solution = new Day5().solution("()[]{}");
// boolean solution = new Day5().solution("([)]");
// boolean solution = new Day5().solution("(]");
boolean solution = new Day5().solution("{[]}");
System.out.println(solution);
}
public boolean solution(String s){
if (s == null || s.length() == 0){
return false;
}
Stack<Character> stack = new Stack<>();
stack.push(s.charAt(0));
for (int i = 1; i < s.length(); i++) {
Character temp = s.charAt(i);
if (stack.size() == 0 || !isMatch(stack.peek(),temp)){
stack.push(temp);
}else {
stack.pop();
}
}
if (stack.size() == 0){
return true;
}
return false;
}
public boolean isMatch(Character a,Character b){
if ((a == '(' && b ==')') || (a == '[' && b == ']') || (a == '{' && b == '}')){
return true;
}else{
return false;
}
}
}