LeetCode之有效括号问题

问题描述:
由于只包含字符的字符串’(’,’)’,’{’,’}’,’[‘和’]’,确定输入字符串是有效的。

如果输入字符串有效:

必须使用相同类型的括号关闭左括号。
必须以正确的顺序关闭左括号。
请注意,空字符串也被视为有效。
例1:
输入: “()”
输出: true
例2:
输入: “()[] {}”
输出: true
例3:
输入: “(]”
输出: false
例4:
输入: “([]]”
输出: false
例5:
输入: “{[]}”
输出: true
如果是一种类型的括号可以用计数器解决左括号+1,右括号-1,但是3种括号就要用到堆栈解决。附上2个代码,第一个是我写的,第二个是答案。

  public boolean isValid(String s) {
            Stack<Character> stack = new Stack<>();
            Map<Character,Character> map = new HashMap<>(16);
            map.put('[',']');
            map.put('{','}');
            map.put('(',')');
            char[] c = s.toCharArray();
            for(char temp:c){
                if(temp=='['||temp=='{'||temp=='('){
                    stack.push(temp);
                }
                if(temp==']'||temp=='}'||temp==')'){
                    if(stack.empty()){
                        return false;
                    }else{
                        if(temp!=map.get(stack.pop())){
                            return false;
                        }
                    }
                }
            }
            if(!stack.empty()){
                return false;
            }
               return true;
        }

第二个

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();
  }
}

猜你喜欢

转载自blog.csdn.net/qq_27817327/article/details/83110380