20. Valid Parentheses

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

思路:

  1. 将‘{’和‘}’、‘[’和‘]’、’(‘和‘)’放入到HashMap中
  2. 遍历字符串s,将‘{’‘[’‘(’入栈,如果是‘]’或‘}’或‘)’从map中取出其对应的字符和栈顶元素比较,相等出栈,否则,返回false;
  3. 判断栈中的元素是否为空,为空返回true,否则,返回false;

细节问题:

  1. 如果case为“}”或者“](){}”,是不是应该单独在考虑下,首字符的问题。有两种做法:第1种做法:先判断首字符,不为‘(’、‘{’、‘[’,直接返回false;第2种做法:在遍历字符串s中,通过使用标记位进行判断。

测试的所有case:

        println(s.isValid("()[]{}"));
        println(s.isValid("()"));
        println(s.isValid("()}"));
        println(s.isValid("}()"));
        println(s.isValid("([)]"));
        println(s.isValid("}"));
        println(s.isValid(""));

代码:

        if (s == null || s.equals(""))
            return true;
        Stack<Character> stack = new Stack<>();
        Map<Character, Character> map = new HashMap<>();
        map.put(')', '(');
        map.put(']', '[');
        map.put('}', '{');
        char ch = '0';

        boolean isFirst = true;
        for (int i = 0; i < s.length(); i++) {
            ch = s.charAt(i);
            if ('(' == ch || '{' == ch || '[' == ch) {
                stack.push(ch);
                isFirst = false;
            } else {
//              处理“]”类型的case;
                if (isFirst) {
                    return false;
                }
                if (!stack.empty() && stack.peek() == map.get(ch)) {
                    stack.pop();
                } else {
                    return false;
                }
            }
        }
        if (stack.empty()) {
            return true;
        } else {
            return false;
        }

遇到问题:

编程的过程中,用到了Stack 对象 stack,stack.empty()和stack.isEmpty()两种方法的区别和联系,百度了下没有搜到?


  • API是这样说的:

isEmpty()方法:—该方法是Vector类中的方法,Stack类继承了Vector
public boolean isEmpty()
测试此向量是否不包含组件。
指定者:
接口 Collection 中的 isEmpty
指定者:
接口 List 中的 isEmpty
覆盖:
类 AbstractCollection 中的 isEmpty
返回:
当且仅当此向量没有组件(也就是说其大小为零)时返回 true;否则返回 false。


empty()方法:
empty
public boolean empty()
测试堆栈是否为空
返回:
当且仅当堆栈中不含任何项时返回 true;否则返回 false。

不知您是否看出来了什么???明白吗?

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值