题目描述
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:
题目大意:
'(', ')', '{', '}', '[' 和']' ,的字符串,要求判定是否是合法的。 class Solution {
public:
bool isValid(string s) {
int top=-1,index=0,length=s.size();
char* stack=(char*)malloc(sizeof(char)*length);
//stack<char> stack;
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;
}
};
代码2:
class Solution {
public:
bool isValid(string s) {
int index=0,length=s.size();
stack<char> st;
while(index<length)
{
if(s[index]==')')
{
if(!st.empty() && st.top()=='(') st.pop(); //弹出
else return false;
}
else if(s[index]=='}')
{
if(!st.empty() && st.top()=='{') st.pop(); //弹出
else return false;
}
else if(s[index]==']')
{
if(!st.empty() && st.top()=='[') st.pop(); //弹出
else return false;
}
else
st.push(s[index]);
index++;
}
return st.empty(); //成对出现,最后栈一定为空;
}
};