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

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

  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,从而实现整个操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值