给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
#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;
}
};
本文介绍了一种使用栈数据结构来判断字符串中括号是否有效配对的方法。通过迭代字符串,利用栈进行开闭括号的匹配,最终验证括号序列的有效性。此算法适用于编程面试和技术挑战。
4885

被折叠的 条评论
为什么被折叠?



