Valid Parentheses (LeetCode #20)
Alex Sikorski

Alex Sikorski

May 30, 2022

Valid Parentheses (LeetCode #20)

#leetcode easy

#leetcode

#java

The problem starts by giving us the definition of a valid string:

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

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "()[]{}"
Output: true

Example 3:

Input: s = "(]"
Output: false

Constraints:

  1. 1 <= s.length <= 104
  2. s consists of parentheses only '()[]{}'.

Initial Solution

class Solution {
    public boolean isValid(String s) {
        
        if(s.length() == 0) return true;
        // if empty string return true

        Stack<Character> LIFOStack = new Stack<>();
        // Last In First Out
        
        for(int i = 0; i < s.length(); i++){
            if(s.charAt(i) == '(' || s.charAt(i) == '{'|| s.charAt(i) == '['){
                LIFOStack.push(s.charAt(i));
                // if open bracket, push to stack
            }
            else if(!LIFOStack.empty() && s.charAt(i) == ')' && LIFOStack.peek() == '('){
                // if close bracket and top of stack is open bracket (and check if empty always)
                LIFOStack.pop();
                // remove respective open bracket from stack
            }
            else if(!LIFOStack.empty() && s.charAt(i) == '}' && LIFOStack.peek() == '{'){
                LIFOStack.pop();
                // repeat for other types of brackets
            }
            else if(!LIFOStack.empty() && s.charAt(i) == ']' && LIFOStack.peek() == '['){
                LIFOStack.pop();
            }
            else{
                return false;
            }
        }
        
        return LIFOStack.empty();
        // if stack is empty, input string is valid
    }
}

Initial Result

2022-05-30 19_11_44-Valid Parentheses - LeetCode — Mozilla Firefox.png

Optimised Solution

The solution below does not use a Java Stack object. Instead, it uses a primitive char array.

class Solution {
    public boolean isValid(String s) {
        char[] stack = new char[s.length()];
        // create char array with s.length() as size
        // s.length() as if String is valid, the program will iterate throughout
		int head = 0;
        // set head index to 0
		for(char c : s.toCharArray()) {
            // iterate through characters in String
			switch(c) {
				case '{':
				case '[':
				case '(':
					stack[head++] = c;
                    // if open bracket, set head index to char then postfix
                    // increment for next iteration
					break;
				case '}':
					if(head == 0 || stack[--head] != '{') return false;
                    // if head is zero, means that no open brackets have been placed in stack
                    // check precending character (prefix decrement), 
                    // if not valid (not { in this case) return false
					break;
				case ')':
					if(head == 0 || stack[--head] != '(') return false;
                    // same logic applies but with other bracket types
					break;
				case ']':
					if(head == 0 || stack[--head] != '[') return false;
					break;
			}
		}
		return head == 0;
    }
}

Optimised Result

2022-05-31 12_15_07-Valid Parentheses - LeetCode — Mozilla Firefox.png

Alex Sikorski

Alex Sikorski

Currently working as a full stack Software Engineer and curiously seeking new knowledge in free time.

Leave a comment

Categories