728x90
Description
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type.
Solution
class Solution{
public boolean isValid(String s){
Stack<Character> stack = new Stack<Character>();
for(char c : s.toCharArray()){
if(c == '(')
stack.push(')');
else if(c == '{')
stack.push('}');
else if(c == '[')
stack.push(']');
else if( stack.isEmpty() || stack.pop != c)
return false;
}
return stack.isEmpty();
}
}
}
Shhhh.. didn't check that the open brackets are closed in the correct order.
https://leetcode.com/problems/valid-parentheses/?envType=study-plan-v2&envId=top-interview-150
'Programming > LeetCode' 카테고리의 다른 글
[LeetCode] #232. Implement Queue using Stacks (0) | 2024.02.05 |
---|---|
[Leetcode] #14. Longest Common Prefix (repeat : 0 ) (0) | 2024.01.31 |
[LeetCode] #58. Length of Last Word (repeat : 0) (2) | 2024.01.23 |
[LeetCode]#13. Roman to Integer (repeat : 0 ) (0) | 2024.01.22 |
[LeetCode] #169. Majority Element (repeat : 0 ) (0) | 2024.01.21 |