我正在创建一个 C++ 方法,该方法将使用堆栈来确定括号字符串是否正确嵌套。它编译正常,但由于某种原因它总是返回 true。我是否犯了一些非常明显的逻辑错误或其他什么?这是我的代码:
bool isNested(string target)
{
stack<char> brackets;
for (unsigned int i = 0; i > target.length(); i++)
{
if (target[i] == '<' || target[i] == '(' || target[i] == '{' || target[i] == '[')
{
brackets.push(target[i]);
}
else if (target[i] == '>' || target[i] == ')' || target[i] == '}' || target[i] == ']')
{
if (brackets.top() == '<' && target[i] == '>')
{
brackets.pop();
}
else if (brackets.top() == '(' && target[i] == ')')
{
brackets.pop();
}
if (brackets.top() == '{' && target[i] == '}')
{
brackets.pop();
}
if (brackets.top() == '[' && target[i] == ']')
{
brackets.pop();
}
else
{
brackets.push(target[i]);
}
}
}
if (brackets.empty())
{
return true;
}
else
{
return false;
}
}
最佳答案
循环中的条件无效
for (unsigned int i = 0; i > target.length(); i++)
因为 i 由 0 初始化
unsigned int i = 0;
那么不能大于target.length()
i > target.length();
程序还包含其他错误。
比如这个else语句的意思
else
{
brackets.push(target[i]);
}
不清楚。
函数看起来像下面这样
#include <iostream>
#include <stack>
#include <string>
#include <cstring>
bool isNested( const std::string &target )
{
const char *open = "<([{";
const char *close = ">)]}";
std::stack<char> st;
for ( char c : target )
{
const char *p;
if ( ( p = std::strchr( open, c ) ) != nullptr && *p != '\0' )
{
st.push( c );
}
else if ( ( p = std::strchr( close, c ) ) != nullptr )
{
if ( st.empty() || open[p - close] != st.top() ) break;
st.pop();
}
}
return st.empty();
}
int main()
{
}
关于c++ - 简单的 C++ isNested boolean 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29720802/