leetcode20 有效的括号

举报
兔老大 发表于 2021/05/07 05:37:11 2021/05/07
【摘要】 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 有效字符串需满足: 左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。 示例 1: 输入: "()" 输出: true 示例 2: 输入: "()[]{}" 输出: true 示例 3: 输...

给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true
示例 2:

输入: "()[]{}"
输出: true
示例 3:

输入: "(]"
输出: false
示例 4:

输入: "([)]"
输出: false
示例 5:

输入: "{[]}"
输出: true

思路:

初始化栈 S。

  1. 一次处理表达式的每个括号。
  2. 如果遇到开括号,我们只需将其推到栈上即可。这意味着我们将稍后处理它,让我们简单地转到前面的 子表达式。
  3. 如果我们遇到一个闭括号,那么我们检查栈顶的元素。如果栈顶的元素是一个 相同类型的 左括号,那么我们将它从栈中弹出并继续处理。否则,这意味着表达式无效。
  4. 如果到最后我们剩下的栈中仍然有元素,那么这意味着表达式无效。

  
  1. class Solution {
  2. // Hash table that takes care of the mappings.
  3. private HashMap<Character, Character> mappings;
  4. // Initialize hash map with mappings. This simply makes the code easier to read.
  5. public Solution() {
  6. this.mappings = new HashMap<Character, Character>();
  7. this.mappings.put(')', '(');
  8. this.mappings.put('}', '{');
  9. this.mappings.put(']', '[');
  10. }
  11. public boolean isValid(String s) {
  12. // Initialize a stack to be used in the algorithm.
  13. Stack<Character> stack = new Stack<Character>();
  14. for (int i = 0; i < s.length(); i++) {
  15. char c = s.charAt(i);
  16. // If the current character is a closing bracket.
  17. if (this.mappings.containsKey(c)) {
  18. // Get the top element of the stack. If the stack is empty, set a dummy value of '#'
  19. char topElement = stack.empty() ? '#' : stack.pop();
  20. // If the mapping for this bracket doesn't match the stack's top element, return false.
  21. if (topElement != this.mappings.get(c)) {
  22. return false;
  23. }
  24. } else {
  25. // If it was an opening bracket, push to the stack.
  26. stack.push(c);
  27. }
  28. }
  29. // If the stack still contains elements, then it is an invalid expression.
  30. return stack.isEmpty();
  31. }
  32. }

 

 

文章来源: fantianzuo.blog.csdn.net,作者:兔老大RabbitMQ,版权归原作者所有,如需转载,请联系作者。

原文链接:fantianzuo.blog.csdn.net/article/details/103239697

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。