Valid Parentheses之Java实现

发布时间:2020-07-03 00:16:32 作者:xiezh10
来源:网络 阅读:252
一、题目

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
  Open brackets must be closed by the same type of brackets.
  Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
  Input: "()"
  Output: true
Example 2:
  Input: "()[]{}"
  Output: true
Example 3:
  Input: "(]"
  Output: false
Example 4:
  Input: "([)]"
  Output: false
Example 5:
  Input: "{[]}"
  Output: true

二、解题思路

1、利用List集合实现一个栈;
2、将字符串s转换成字符数组,并循环遍历;
3、如果字符为:"{、(、["中的一个,则存入集合中;
4、如果字符为:"}、)、]"中的一个,则取出集合中最后一个元素进行比较;
5、如能匹配上,则删除集合中最后一个元素,否则返回false;
6、最后判断集合大小是否为0,如是则返回true。

三、代码实现
public boolean isValid(String s) {
    if ("".equals(s)) {
        return true;
    } else {
        Map<Character, Character> parentheseMap = new HashMap<Character, Character>();
        parentheseMap.put(')', '(');
        parentheseMap.put(']', '[');
        parentheseMap.put('}', '{');        
        char[] sArr = s.toCharArray();
        List<Character> stackList = new ArrayList<Character>();
        for (int i = 0; i < sArr.length; i++) {
            if (sArr[i] == '(' || sArr[i] == '[' || sArr[i] == '{') {
                stackList.add(sArr[i]);
            } else {
                if (stackList.size() == 0) {
                    return false;
                } else {
                    char temp = stackList.get(stackList.size() - 1);
                    if (temp == parentheseMap.get(sArr[i])) {
                        stackList.remove(stackList.size() - 1);
                    } else {
                        return false;
                    }
                }
            }
        }
        return stackList.size() == 0 ? true : false;
    }
}
推荐阅读:
  1. iOS错误之“A valid provisioning profile for this executable was not found”
  2. [LeetCode]32. Longest Valid Parentheses

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

leetcode java valid parentheses

上一篇:通过sprintf函数来实现的进制转换

下一篇:【学习笔记】Android控件的使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》