🍣一道算法题🏵
题目:给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
示例 1:
输入:s = "()"
输出:true
示例 2:
输入:s = "()[]{}"
输出:true
示例 3:
输入:s = "(]"
输出:false
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
解法一:成对去除法(好用)
//方法部分:
private static boolean method(String br) {
//提高效率
if(br==null||br.length()==0||br.startsWith(")")||br.startsWith("]")||br.startsWith("}")){
return false;
}
//通过循环去除符合条件的括号
while(br.contains("()")||br.contains("[]")||br.contains("{}")){
System.out.println(br);
if(br.contains("()")){
br=br.replace("()","");
}else if(br.contains("[]")){
br= br.replace("[]","");
}else if(br.contains("{}")){
br=br.replace("{}","");
}
}
if(br.length()==0){
return true;
}
return false;
}
//========================测试部分=======================================
public static void main(String[] args) throws IOException {
//通过流获取用户输入的字符串
System.out.println("请输入字符串:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//成对去除法
boolean is=method(br.readLine());
System.out.println(is);
}
测试结果:::

解法二:使用栈
- 通过栈,栈内只存’(’’{’’[’,与栈顶元素进行判断,最后返回值要看栈内有没有元素
//栈方法
private static boolean method01(String readLine) {
//提高效率
if(readLine==null||readLine.length()<2||readLine.startsWith(")")||readLine.startsWith("]")||readLine.startsWith("}")){
return false;
}
//创建一个栈对象
Stack<Character> sc=new Stack<>();
for (Character ch: readLine.toCharArray()) {
if(ch=='['||ch=='('||ch=='{'){
sc.push(ch);
}else if(sc.isEmpty()){//防止括号不对()))
return false;
}else{
Character pop=sc.pop();//获取栈顶元素
//这里的判断要注意
if(!(pop=='{'&&ch=='}'||pop=='['&&ch==']'||pop=='('&&ch==')')){
return false;
}
}
}
return sc.isEmpty();//只要栈里不是空就代表true
}
结果:

🍤🍤🍤(⊙﹏⊙)!!!
本文探讨了如何解决LeetCode中的有效括号问题,介绍了两种方法:成对去除法和栈的应用,通过实例展示了如何判断给定字符串中括号的有效性。
784

被折叠的 条评论
为什么被折叠?



