有效的括号

有效的括号valid-parentheses

题目

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

有效字符串需满足:

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

示例 1:

输入: "()"
输出: true

示例 2:

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

示例 3:

输入: "(]"
输出: false

示例 4:

输入: "([)]"
输出: false

示例 5:

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

程序

代码1

算法

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

import java.util.Stack;

public class Solution {
    
    /**如果是左括号,压入栈,如果是右括号,弹出比较*/
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        char[] chars = s.toCharArray();
        boolean isValid = true;
        for(char aChar : chars) {
            if(isLeft(aChar)) {
                stack.add(aChar);
            }else {
                if(stack.size()>0) {
                    isValid = isValid && isSym(stack.pop(), aChar);
                }else {
                    return false;
                }
            }
        }
        
        //判断是否已全部出栈
        if(stack.size()>0) {
            return false;
        }
        return isValid;
    }
    
    /**判断是否是左括号*/
    private boolean isLeft(char s) {
        if(s=="(".charAt(0)||s=="{".charAt(0)||s=="[".charAt(0)) {
            return true;
        }else {
            return false;
        }
    }
    
    /**判断是否配对*/
    private boolean isSym(char c1, char c2) {
        return (c1 == '(' && c2 == ')') || (c1 == '[' && c2 == ']') || (c1 == '{' && c2 == '}');
    }
    
    public static void main(String[] args) {
        Solution solu = new Solution();
        System.out.print(solu.isValid("()[]{}"));
    }
}   

执行结果:

通过
显示详情
执行用时 :
2 ms, 在所有 java 提交中击败了96.05%的用户
内存消耗 :34 MB, 在所有 java 提交中击败了88.87%的用户

代码2

官方写法

class Solution {

  // Hash table that takes care of the mappings.
  private HashMap<Character, Character> mappings;

  // Initialize hash map with mappings. This simply makes the code easier to read.
  public Solution() {
    this.mappings = new HashMap<Character, Character>();
    this.mappings.put(')', '(');
    this.mappings.put('}', '{');
    this.mappings.put(']', '[');
  }

  public boolean isValid(String s) {

    // Initialize a stack to be used in the algorithm.
    Stack<Character> stack = new Stack<Character>();

    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);

      // If the current character is a closing bracket.
      if (this.mappings.containsKey(c)) {

        // Get the top element of the stack. If the stack is empty, set a dummy value of '#'
        char topElement = stack.empty() ? '#' : stack.pop();

        // If the mapping for this bracket doesn't match the stack's top element, return false.
        if (topElement != this.mappings.get(c)) {
          return false;
        }
      } else {
        // If it was an opening bracket, push to the stack.
        stack.push(c);
      }
    }

    // If the stack still contains elements, then it is an invalid expression.
    return stack.isEmpty();
  }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 有效字符串需满足:...
    bocsoft阅读 4,371评论 0 0
  • 题目 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。有效字符串需满...
    就是会把话说反阅读 1,436评论 0 0
  • 题目描述: 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。有效字符...
    夜空中最亮的星_6c64阅读 1,706评论 0 0
  • 0. 序言 "有效的括号"这一题,可以帮助我们更好的理解栈这个数据结构。 1. 题目描述 给定一个只包括'(','...
    付凯强阅读 3,315评论 0 2
  • 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。有效字符串需满足:1...
    小王子特洛伊阅读 3,068评论 0 0

友情链接更多精彩内容