给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
#include <iostream>
#include <stack>
using namespace std;
class Solution {
public:
bool isValid(string s) {
bool flag = false;
stack<char> st;
int l;
int r;
if(s.size() == 0)
return true;
string::iterator ite = s.begin();
st.push(*ite);
ite++;
while( ite != s.end()){
if(st.empty()){
st.push(*ite);
ite++;
continue;
}
l = (int)(st.top());
r = (int)(*ite);
if( (l-r)==1 || (l-r)==2 || (l-r)==-1 || (l-r)==-2 ) {
st.pop();
}else{
st.push(*ite);
}
ite++;
}
if(st.empty()){
flag = true;
}
return flag;
}
};
后来觉得有点不好, 可能连 ][ 都能匹配在一起通过, 然后改了一下:
#include <iostream>
#include <stack>
using namespace std;
class Solution {
public:
bool isValid(string s) {
if(s.length()==0)
return true;
stack<char> st;
string::iterator ite = s.begin();
st.push(*ite);
ite++;
while (ite != s.end()) {
if(st.empty()){
st.push(*ite);
ite++;
continue;
}
if( *ite=='(' || *ite=='{' || *ite=='[' ){
st.push(*ite);
}
if( *ite==')' || *ite=='}' || *ite==']' ){
if( (*ite-st.top())==1 || (*ite-st.top())==2 ){
st.pop();
}else{
st.push(*ite);
}
}
ite++;
}
if(st.empty()){
return true;
}
return false;
}
};