题目描述:
//给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
//有效字符串需满足:
//左括号必须用相同类型的右括号闭合。
//左括号必须以正确的顺序闭合。
//注意空字符串可被认为是有效字符串。
//示例 1:输入: “()” 输出: true
//示例 2:输入: “()[]{}” 输出: true
//示例 3:输入: “(]” 输出: false
//示例 4:输入: “([)]” 输出: false
//示例 5:输入: “{[]}” 输出: true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
本地调试代码:
public class LeetCode20 {
private HashMap<Character,Character> dataBase;
public LeetCode20(){
this.dataBase=new HashMap<Character, Character>();
this.dataBase.put(')','(');
this.dataBase.put('}','{');
this.dataBase.put(']','[');
}
public static void main(String[] args){
new LeetCode20().isValid("(}");
}
public boolean isValid(String s) {
//如果字符串的长度为奇数,直接返回false
if(s.length()%2==1){
return false;
}
//新建一个空栈
Stack<Character> stack=new Stack<Character>();
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
//判断dataBase存不存在key值为c的
if(this.dataBase.containsKey(c)){
//如果存在就进行出栈操作-->取出栈顶元素,进行比较
char topValue=stack.empty()?'#':stack.pop();
//能取到value值的key有')' ,'}' ,']',故'(' ,'{' ,'['为入栈。
//假设c为 ')' ,this.dataBase.get(c)取到的value值为:'('。
//如果栈顶元素和key为c的value值为相等,则证明为有效闭合。不一致则为无效闭合,直接返回false即可。
//如果为有效闭合,则继续进行循环,由于上步操作已经将栈顶取出-1。故无需再处理有效闭合的字符。
if(topValue!=this.dataBase.get(c)){
return false;
}
}else{
//如果不存在,就将此c入栈
stack.push(c);
}
}
return stack.empty();
}
}
力扣验证提交的代码:
class Solution {
private HashMap<Character, Character> dataBase;
public Solution() {
this.dataBase = new HashMap<Character, Character>();
this.dataBase.put(')', '(');
this.dataBase.put('}', '{');
this.dataBase.put(']', '[');
}
public boolean isValid(String s) {
if (s.length() %2 == 1) {
return false;
}
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (this.dataBase.containsKey(c)) {
char topValue = stack.empty() ? '#' : stack.pop();
if (topValue != this.dataBase.get(c)) {
return false;
}
} else {
stack.push(c);
}
}
return stack.empty();
}
}