1 ms Java Sol using Stack


  • 2

    Stack usage simplifies the solution.
    Correct use of Data Structure.
    Keep pushing till you find any of these '{', '[', '('
    Anything else Pop and check if the opposite is popped out. If not return false.

    public class Solution {
        public boolean isValid(String s) {
            Stack<Character> strings = new Stack<Character>();
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == '{' || s.charAt(i) == '(' || s.charAt(i) == '[') {
                    strings.push(s.charAt(i));
                }
                if (s.charAt(i) == '}') {
                    if (strings.isEmpty() || strings.pop() != '{') {
                        return false;
                    }
                } else if (s.charAt(i) == ')') {
                    if (strings.isEmpty() || strings.pop() != '(') {
                        return false;
                    }
                } else if (s.charAt(i) == ']') {
                    if (strings.isEmpty() || strings.pop() != '[') {
                        return false;
                    }
                }
            }
            if (strings.isEmpty()) {
                return true;
            }
            return false;
        }
    }
    

  • 0

    Actually your answer need to run 6ms , but it's good


Log in to reply
 

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