力扣刷题之栈---第二十题有效的括号

这是一道简单的题目,方法为利用栈针对数据的先入后出的特性进行解题。单从题目看,输入成立的可能总共有三种,分别为 :

  1. “()[]{}”,两两相结合,中间不含有其他类型括号
  2. “{[]}”,形成一个对称的形式,从中间区分左边和右边分别为括号的左边和右边。
  3. 前两种进行结合。
    对于此题栈的方法毫无疑问最为高效,复杂度为n,将左括号和右括号对应关系变为哈希表,键值对。针对输入进行遍历,左括号放入哈希表中,一旦出现右括号则进行判断,如果与栈中的top元素相对应,则将栈中元素抛出,接着进行判断,否则直接返回false。
    代码如下:
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();
   }
}

作者:LeetCode链接:https://leetcode-cn.com/problems/valid-parentheses/solution/you-xiao-de-gua-hao-by-leetcode/
这种做法十分巧妙,首先因为左括号必须存入栈中,同时之后会根据右括号去判断是否满足,因此将左括号设为值,将右括号设为key,之后如果发现输入为哈希表中包含的key,则去判断该key所对应value值是否跟顶端的元素相同,通过key去取值value,从而实现整个操作。

发布了24 篇原创文章 · 获赞 6 · 访问量 518

猜你喜欢

转载自blog.csdn.net/qq_35065720/article/details/103375644