判断一个字符串是否为嵌套字符串,如{([()])}, {()}(0){}[{}]
嵌套判断标准:{}[]()特定字符匹配
{([()])} 是
{()}(0){}是
{[}] 不是
结束标志:
如果字符串中含有其他非特定符号时,嵌套与否的定义为:迭代字符为\0,且栈中没有特定字符。(本文代码假设条件)
如果字符串中只有特定字符,嵌套与否的标准为:迭代字符为\0,且栈中为空。
#include <iostream> #include <stack> using namespace std; void charMatch(const char* str) { stack<char> charStack; if(str==NULL){ cout << "the string is NULL..." <<endl; return; } while(*str != '\0'){ while(*str != '\0' && *str != ']' && *str != '}' && *str != ')'){ cout << *str <<endl; charStack.push(*str); ++str; } if(*str == ']'){ while(!charStack.empty() && charStack.top()!= '['){ charStack.pop(); } if(charStack.empty()){ cout << "string is not match to nest" <<endl; return; } if(charStack.top() == '['){ charStack.pop(); } } if(*str == '}'){ while(!charStack.empty() && charStack.top()!= '{'){ charStack.pop(); } if(charStack.empty()){ cout << "string is not match to nest" <<endl; return; } if(charStack.top() == '{'){ charStack.pop(); } } if(*str == ')'){ while(!charStack.empty() && charStack.top()!= '('){ charStack.pop(); } if(charStack.empty()){ cout << "string is not match to nest" <<endl; return; } if(charStack.top() == '('){ charStack.pop(); } } ++str; } if(*str == '\0' && !charStack.empty()){ while(!charStack.empty() && charStack.top() != '[' && charStack.top() != '{' && charStack.top() != '('){ charStack.pop(); } if(charStack.empty()){ cout << "string is match to nest" <<endl; return; } if(charStack.top() == '[' || charStack.top() == '{' || charStack.top() == '('){ cout << "string is not match to nest" <<endl; return; } } if(*str == '\0' && charStack.empty()){ cout << "string is match to nest" <<endl; return; } } int main(){ string str = "({k[]})["; cout << str <<endl; charMatch(str.c_str()); return 0; }