当前位置:   article > 正文

栈的几道练习题_程序设计栈的例题

程序设计栈的例题

力扣 P20 有效的括号

public class Solution{
    public boolean isValid(String s) {
    	// 空字符串可被认为是有效字符串
        if (s.length() == 0) {
            return true;
        }
        HashMap<Character, Character> hm = new HashMap<>();
        hm.put('(', ')');
        hm.put('[', ']');
        hm.put('{', '}');

        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            // 如果是左括号,入栈
            if (hm.containsKey(c)) {
                stack.push(c);
            }
            // 如果是右括号
            else {
                // 如果能匹配,注意出栈之前都要判断栈是否为空
                if (! stack.isEmpty() && hm.get(stack.peek()) == c) {
                    stack.pop();
                }
                else {
                    return false;
                }
            }
        }
        // 如果字符串只有一个左括号会出错,所以要判断栈是否为空
        return stack.isEmpty() ? true : false;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号