题目描述
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例1:
输入: "()"
输出: true
示例2:
输入: "()[]{}"
输出: true
示例3:
输入: "(]"
输出: false
示例4:
输入: "([)]"
输出: false
示例5:
输入: "{[]}"
输出: true
解题思路
通过栈结构即可,先进后处,类似于括号嵌套
代码示例
public class Test {
public static Map<Character,Character> mapChar = new HashedMap<Character, Character>(){{
//注意map中 key 为 右括号
put('}', '{'); put(']', '['); put(')', '(');
}};
public static void main(String[] args) {
String str = "(){{([])}}[]";
boolean b = isValid(str);
System.out.println("输入的字符串为:"+str);
System.out.println("返回结果为"+b);
}
private static boolean isValid(String str){
int length = str.length();
//长度为奇数直接返回false
if (length%2 != 0){
return false;
}
Stack<Character> stack = new Stack<>();
for (int i = 0; i < length; i++){
Character c = str.charAt(i);
if (!stack.empty() && stack.peek().equals(mapChar.get(c))){
//移除
stack.pop();
}else {
//添加
stack.push(c);
}
}
return stack.isEmpty();
}
}
运行结果
▄█▀█●各位同仁,如果我的代码对你有帮助,请给我一个赞吧,为了下次方便找到,也可关注加收藏呀
如果有什么意见或建议,也可留言区讨论