Problem 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.
Solution:
class Solution {
public boolean isValid(String s) {
String input=s;
boolean flag=true;
Stack<Character> stack = new Stack<Character>();
mainLoop:
for(int i=0; i<input.length(); i++) {
char ch = input.charAt(i);
switch(ch) {
case '(':
case '{':
case '[':
stack.push(ch);
break;
case ')':
if(!stack.empty()){
Character top = (Character)stack.peek();
if(top.compareTo('(') == 0) {
stack.pop();
} else {
flag=false;
break mainLoop;
}
} else {
flag=false;
break mainLoop;
}
break;
case '}':
if(!stack.empty()){
Character top = (Character)stack.peek();
if(top.compareTo('{') == 0) {
stack.pop();
} else {
flag=false;
break mainLoop;
}
} else {
flag=false;
break mainLoop;
}
break;
case ']':
if(!stack.empty()){
Character top = (Character)stack.peek();
if(top.compareTo('[') == 0) {
stack.pop();
} else {
flag=false;
break mainLoop;
}
} else {
flag=false;
break mainLoop;
}
break;
}
}
if (!stack.empty()){
flag=false;
}
return flag;
}
}