Problem:
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.
Solution:
典型的栈应用,用栈解决,复杂度O(n)
题目大意:
给一串只包含有
'('
, ')'
, '{'
, '}'
, '['
和']'
,的字符串,要求判定是否是合法的。Java源代码(用时251ms):
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;
}
}
C语言源代码(1ms):
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;
}
C++源代码(2ms):
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;
}
};
Python源代码(42ms):
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==-1