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.
这一题是典型的使用压栈的方式解决的问题,题目中还有一种valid情况没有说明,需要我们自己考虑的,就是"({[]})"这种层层嵌套但
可以完全匹配的,也是valid的一种。
解题思路是这样的:我们对字符串S中的每一个字符C,如果C不是右括号,就压入栈stack中。
如果C是右括号,判断stack是不是空的,空则说明没有左括号,直接返回not valid,非空就取出栈顶的字符pre来对比,如果是匹配
的,就弹出栈顶的字符,继续取S中的下一个字符;如果不匹配,说明不是valid的,直接返回。当我们遍历了一次字符串S后,注意
这里还有一种情况,就是stack中还有残留的字符没有得到匹配,即此时stack不是空的,这时说明S不是valid的,因为只要valid,一
定全都可以得到匹配使左括号弹出。
class Solution {
public:
bool isValid(string s) {
int len=s.size();
stack<char>charStack;
int i=0;
while(i!=len){
char c=s[i];
if(s[i]!=')'&&s[i]!='}'&&s[i]!=']'){
charStack.push(c);
}
else{
if(charStack.size()==0)//为又括号且栈为空
return false;
char pre=charStack.top();
switch(c)
{
case ')':
if(pre=='(')charStack.pop();
else return false;
break;
case '}':
if(pre=='{')charStack.pop();
else return false;
break;
case ']':
if(pre=='[')charStack.pop();
else return false;
break;
}
}
++i;
}
if(charStack.size()==0)
return true;
else return false;
}
};
Second time
class Solution {
public:
bool isValid(string s) {
int len=s.size();
if (len==0)return false;
stack<char>p;
for(int i=0;i<len;i++){
if((s[i]=='(')||(s[i]=='{')||(s[i]=='['))
p.push(s[i]);
else{
if(p.size()==0)
return false;
char tp=p.top();
p.pop();
if((tp=='{')&&(s[i]!='}'))
return false;
if((tp=='(')&&(s[i]!=')'))
return false;
if((tp=='[')&&(s[i]!=']'))
return false;
}
}
if(p.size()==0) //验证最后栈是否为空,不然多出了左边括号。
return true;
else return false;
}
};
完整程序
#include<iostream>
#include<string>
#include<stack>
using namespace std;
void main(){
string s;
stack<char>p;
cout << "in:" << endl;
cin >> s;
cout << "out:" << endl;
int i;
for (i = 0; i < s.size(); i++){
if ((s[i] == '(' )||( s[i] == '[') || (s[i] == '{'))
p.push(s[i]);
else{
if (p.size() == 0){
cout << "false" << endl; system("pause");
}
char t = p.top();
p.pop();
if ((s[i] == ')') && (t != '(')){
cout << "false" << endl; system("pause");
}
if ((s[i] == ']') && (t != '[')){
cout << "false" << endl; system("pause");
}
if ((s[i] == '}') && (t != '{')){
cout << "false" << endl; system("pause");
}
}
}
if (p.size() == 0){
cout << "true" << endl;
}
else cout << "false" << endl;
system("pause");
}
完整二
#include<iostream>
#include<string>
#include<stack>
using namespace std;
bool isvalued(string s){
stack<char>p;
for (int i = 0; i < s.size(); i++){
if ((s[i] == '(') || (s[i] == '[') || (s[i] == '{'))
p.push(s[i]);
else{
if (p.size() == 0){
return false;
}
char t = p.top();
p.pop();
if ((s[i] == ')') && (t != '(')){
return false;
}
if ((s[i] == ']') && (t != '[')){
return false;
}
if ((s[i] == '}') && (t != '{')){
return false;
}
}
}
if (p.size() == 0){
return true;
}
else return false;
}
void main(){
string s;
cout << "in:" << endl;
cin >> s;
cout << "out:" <<endl;
if (isvalued(s))
cout << "True" << endl;
else cout << "False" << endl;
system("pause");
}