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) {
int length=s.length(),top=-1,index=0;
char[] stack=new char[length];
char[] str=s.toCharArray();
while(index<length){
if(str[index]==')'){
if(top>=0 && stack[top]=='(')top--;
else return false;
}else if(str[index]=='}'){
if(top>=0 && stack[top]=='{')top--;
else return false;
}else if(str[index]==']'){
if(top>=0 && stack[top]=='[')top--;
else return false;
}else stack[++top]=str[index];
index++;
}
return top==-1;
}
}bool isValid(char* s) {
char stack[1000000];
int top=-1;
while(*s){
if(*s==')'){
if(top>=0 && stack[top]=='(')top--;
else return false;
}else if(*s=='}'){
if(top>=0 && stack[top]=='{')top--;
else return false;
}else if(*s==']'){
if(top>=0 && stack[top]=='[')top--;
else return false;
}else stack[++top]=*s;
s++;
}
return top==-1;
}class Solution {
public:
bool isValid(string s) {
int top=-1,index=0,length=s.size();
char* stack=(char*)malloc(sizeof(char)*length);
while(index<length){
if(s[index]==')'){
if(top>=0 && stack[top]=='(')top--;
else return false;
}else if(s[index]=='}'){
if(top>=0 && stack[top]=='{')top--;
else return false;
}else if(s[index]==']'){
if(top>=0 && stack[top]=='[')top--;
else return false;
}else stack[++top]=s[index];
index++;
}
return top==-1;
}
};class Solution:
# @param {string} s
# @return {boolean}
def isValid(self, s):
length=len(s);top=-1;index=0
stack=[' ' for i in range(length)]
while index < length:
if s[index]==')':
if top>=0 and stack[top]=='(':top-=1;
else:return False
elif s[index]=='}':
if top>=0 and stack[top]=='{':top-=1;
else:return False
elif s[index]==']':
if top>=0 and stack[top]=='[':top-=1;
else:return False
else:top+=1;stack[top]=s[index]
index+=1
return top==-1LeetCode 20 Valid Parentheses (C,C++,Java,Python)
原文:http://blog.csdn.net/runningtortoises/article/details/45621933