Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Valid Parentheses
- 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.
- class Solution {
- public boolean isValid(String s) {
- // Create a new stack to store the characters.
- Stack<Character> stack = new Stack<>();
- // convert string into char array and access the characters using for each loop.
- for(char ch: s.toCharArray())
- {
- // check ch
- switch (ch)
- {
- // open bracket then push it in stack.
- // close bracket then pop the item and compare.
- case '(':
- case '{':
- case '[':
- stack.push(ch);
- break;
- case ')':
- if(stack.isEmpty() || stack.pop() != '(')
- // if the stack is empty then it means string have no open bracket.
- // hence it is invalid.
- {
- return false;
- }
- break;
- case '}':
- if(stack.isEmpty() || stack.pop() != '{')
- {
- return false;
- }
- break;
- case ']':
- if(stack.isEmpty() || stack.pop() != '[')
- {
- return false;
- }
- break;
- }
- }
- // After the loop we have to check one more condition.
- // return true only if the stack is empty.
- // if stack is not empty that means we have unused brackets.
- if(stack.isEmpty())
- return true;
- else
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment