Friday, February 28, 2014

Valid Parentheses ( Java + Python)

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.


/*
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
*/
public class Solution {
public boolean isValid(String s) {
if (s==null || s.length()==0){
return true;
}
Stack<Character> checker=new Stack<Character>();
int i=0;
while (i<s.length()){
if (s.charAt(i)=='(' || s.charAt(i)=='[' || s.charAt(i)=='{'){
checker.push(s.charAt(i));
i++;
}
else if (s.charAt(i)==')' || s.charAt(i)==']' || s.charAt(i)=='}'){
if (checker.isEmpty()){
return false;
}
else{
char temp=checker.peek();
if (isPair(temp, s.charAt(i))){
checker.pop();
i++;
}
else{
return false;
}
}
}
else{
return false;
}
}
if (checker.isEmpty() ){
return true;
}
return false;
}
// check is given two chars are pair
private boolean isPair(char c1, char c2){
String validChars="()[]{}";
int indexC1=validChars.indexOf(c1);
int indexC2=validChars.indexOf(c2);
if (indexC1<0||indexC2<0){
return false;
}
if (indexC1+1==indexC2){
return true;
}
return false;
}
}
"""
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
"""
# rewrite at 3/2/2014
class Solution:
# @return a boolean
def isValid(self, s):
if s==None or len(s)==0:
return True
stack=[]
dict={'}':'{', ']':'[',')':'('}
for c in s:
if c=='(' or c=='[' or c=='{':
stack.append(c)
elif dict[c]:
if len(stack)==0:
return False
else:
last=stack[-1]
if dict[c]!=last:
return False
else:
stack.pop()
else:
return False
return len(stack)==0

No comments:

Post a Comment