Skip to content

Latest commit

 

History

History
67 lines (54 loc) · 1.82 KB

_20. Valid Parentheses.md

File metadata and controls

67 lines (54 loc) · 1.82 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : May 22, 2024

Last updated : July 01, 2024


Related Topics : String, Stack

Acceptance Rate : 40.763 %


Solutions

Java

class Solution {
    public boolean isValid(String s) {
        Stack<Character> temp = new Stack<>();

        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '[' || s.charAt(i) == '(' || s.charAt(i) == '{') {
                temp.add(s.charAt(i));
            } else if (s.charAt(i) == ']' || s.charAt(i) == ')' || s.charAt(i) == '}') {
                if (temp.isEmpty()) {
                    return false;
                } else {
                    switch (s.charAt(i)) {
                        case ']' :
                            if (temp.peek() != '[') {
                                return false;
                            }
                            break;
                        case '}' :
                            if (temp.peek() != '{') {
                                return false;
                            }
                            break;
                        case ')' :
                            if (temp.peek() != '(') {
                                return false;
                            }
                            break;
                        default :
                            return false;       
                    }

                    temp.pop();
                }
            }
        }

        return temp.isEmpty();
    }
}