My ugly java code but the algorithm is simple


  • 0
    F
    public boolean isValid(String s) {
        char[] chars = s.toCharArray();
        LinkedList<Character> characters = new LinkedList<>();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '(' || chars[i] == '[' || chars[i] == '{') {
                characters.addLast(chars[i]);
            } else {
                if (characters.isEmpty()) {
                    return false;
                } else {
                    if (!isMatch(characters.removeLast(), chars[i])) {
                        return false;
                    }
                }
            }
        }
        return characters.size() == 0;
    }
    
    public boolean isMatch(char a, char b) {
        return (a == '(' && b == ')') || (a == '[' && b == ']') || (a == '{' && b == '}');
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.