欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 游戏 > 【Hot100】LeetCode—20. 有效的括号

【Hot100】LeetCode—20. 有效的括号

2026/1/31 14:39:37 来源:https://blog.csdn.net/weixin_44382896/article/details/141816820  浏览:    关键词:【Hot100】LeetCode—20. 有效的括号

目录

  • 1- 思路
    • 栈实现
  • 2- 实现
    • ⭐20. 有效的括号——题解思路
  • 3- ACM 实现


  • 原题链接:20. 有效的括号

1- 思路

栈实现

  • 遇到一个左括号,将对应的右括号压栈处理
  • 否则弹出栈顶元素,比较和当前括号是否一致,不一致返回 false
    • 三种情况
    • ① 左右不匹配
    • ② 左多右少,判断在 最后返回 st.isEmpty()
    • ③ 左少右多,判断在 else if(st.isEmpty() || c != st.peek())

2- 实现

⭐20. 有效的括号——题解思路

在这里插入图片描述

class Solution {public boolean isValid(String s) {int len = s.length();if(len%2!=0) return false;// 压栈Stack<Character> st = new Stack<>();for(int i =0 ; i < s.length() ;i++){char c = s.charAt(i);if(c == '('){st.push(')');}else if(c == '['){st.push(']');}else if(c == '{'){st.push('}');}else if(st.isEmpty() || c != st.peek()){return false;}else {st.pop();}}return st.isEmpty();}
}

3- ACM 实现

public class validK {public static boolean isValid(String str){// 遍历int len = str.length();if(len%2!=0) return false;Stack<Character> st = new Stack<>();for(int i = 0 ; i < str.length() ; i++) {char c = str.charAt(i);if(c == '('){st.push(')');}else if(c == '['){st.push(']');}else if(c == '{'){st.push('}');}else if (st.isEmpty() || c != st.peek()){return false;}else {st.pop();}}return st.isEmpty();}public static void main(String[] args) {Scanner sc = new Scanner(System.in);String input = sc.nextLine();System.out.println("结果是"+isValid(input));}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词