Note that an empty string is also considered valid.
Input: "()[]{}"
Output: true
Input: "(]"
Output: false
Input: "([)]"
Output: false
Input: "{[]}"
Output: true
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(char c : s.toCharArray()){
if(c == '(' || c =='[' || c =='{'){
stack.push(c);
continue;
}
if(stack.isEmpty() ||transfer(c) != stack.peek() ){
return false;
}else if(!stack.isEmpty()){
stack.pop();
}
}
return stack.isEmpty();
}
public char transfer(Character c){
if(c == ']')
return '[';
else if(c == '}'){
return '{';
}
else if(c == ')'){
return '(';
}else{
return '\0';
}
}
}
public boolean isValidParentheses(String s) {
// Write your code here
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
}
if (c == ')') {
if (stack.isEmpty() || stack.pop() != '(') {
return false;
}
}
if (c == ']') {
if (stack.isEmpty() || stack.pop() != '[') {
return false;
}
}
if (c == '}') {
if (stack.isEmpty() || stack.pop() != '{') {
return false;
}
}
}
return stack.isEmpty();
}