4.12
public class Solution {
/**
* @param s A string
* @return whether the string is a valid parentheses
*/
public boolean isValidParentheses(String s) {
LinkedList<Character> stack = new LinkedList<Character>();
int l = s.length();
if(l == 0){
return false;
}
if(l % 2 != 0){
return false;
}
for(int i = 0;i < l;i++){
if(s.charAt(i) == '(' || s.charAt(i) == '['|| s.charAt(i) == '{'){
stack.addFirst(s.charAt(i));
continue;
}
else if(s.charAt(i) == ')'){
if(stack.isEmpty()){
return false;
}
else{
char tmp = stack.pop();
if( tmp != '('){
return false;
}
}
}
else if(s.charAt(i) == ']'){
if(stack.isEmpty()){
return false;
}
else{
char tmp = stack.pop();
if( tmp != '['){
return false;
}
}
}
else if(s.charAt(i) == '}'){
if(stack.isEmpty()){
return false;
}
else{
char tmp = stack.pop();
if( tmp != '{'){
return false;
}
}
}
}
if(stack.isEmpty()){
return true;
}
else{
return false;
}
// Write your code here
}
}