Valid Parenthesis LeetCode
class Solution {
public boolean isValid(String str) {
Stack<Character> stack=new Stack<Character>();
for(int i=0;i<str.length();i++){
if(stack.isEmpty()){
stack.push(str.charAt(i));
}
else if(stack.peek()=='{' && str.charAt(i)=='}'){
stack.pop();
}
else if(stack.peek()=='[' && str.charAt(i)==']'){
stack.pop();
}
else if(stack.peek()=='(' && str.charAt(i)==')'){
stack.pop();
}
else{
stack.push(str.charAt(i));
}
}
if(stack.isEmpty()){
return true;
}
else{
return false;
}
}
}
Comments
Post a Comment