java - 检查嵌套在字符串中的括号

标签 java algorithm data-structures

我参加了一个关于 Codility 的训练挑战,检查字符串中括号的嵌套是否正确。要检查的括号是{,},(,),[,]。我写了下面的 java 程序,它在 O(n) 的时间和空间中传递,但我有一种感觉,我使用的额外空间可以减少。另外我认为必须有一种数据结构可以更有效地处理这种情况。使用 ArrayList 而不是数组可能会有所帮助。我在这里需要的是对我的代码的批评。提前致谢。

这是我写的代码:

import java.util.HashMap;
class Solution {
    public int solution(String S) {
        char[] stack = new char[S.length()];
        int last = -1;
        HashMap hm = new HashMap();
        hm.put('}', '{');
        hm.put(')', '(');
        hm.put(']', '[');
        for(int i=0; i<S.length(); i++){
            char next = S.charAt(i);
            if(next == '}' || next == '{' || next == ')' || next == '(' ||
            next == ']' || next == '[')
            {
                if(last!=-1 && hm.containsKey(next) && stack[last] == hm.get(next)){
                    last--;
                }
                else{
                    last++;
                    stack[last] = S.charAt(i);
                }
            }
        }
        if(last == -1){
            return 1;
        }
        return 0;
    }
}

最佳答案

这是一个带有列表的解决方案:

import java.util.LinkedList;    

class Solution {

    public int solution(String S) {
        LinkedList<Character> stack = new LinkedList<>();

        for (int i = 0; i < S.length(); i++) {
            char c = S.charAt(i);

            if (c == '{' || c == '[' || c == '(') {
                stack.push(c);
            } else {
                if (stack.isEmpty()) {
                    return 0;
                }

                char preceding = stack.pop();

                if (c == ')' && preceding != '(') {
                    return 0;
                }

                if (c == ']' && preceding != '[') {
                    return 0;
                }

                if (c == '}' && preceding != '{') {
                    return 0;
                }

            }
        }

        return stack.isEmpty() ? 1 : 0;
    }
}

关于java - 检查嵌套在字符串中的括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21789787/

相关文章:

algorithm - 如何证明堆中最坏情况下的反转次数是Ω(nlogn)?

c++ - 键为 2 的幂的快速映射 (C++)

java - 如果他在相同或不同的浏览器上再次登录,如何注销用户的先前 session

java - 比较 Java 中列表映射中的每个对象

algorithm - 后缀树 VS 尝试 - 用简单的英语来说,有什么区别?

algorithm - Prolog中信息检索的性能优化

c - 将较小结构的数组移动到 C 中较大结构的数组中

java - 为什么如果我从 IDE (Eclipse) 启动一个 Spring Boot 应用程序作为 Java 应用程序,它可以工作,但是当我从 CMD 启动它时,它会出现 Whitelabel 错误?

java - 用j2me中的字符串替换字符串

algorithm - SHA-2 的空间和时间复杂度