应该比较容易理解,完整代码如下:
#include#include #include #include using namespace std; bool isValid(string s) { stack sta; for (int i = 0; i < s.length(); i++) { if (s[i] == '(' || s[i] == '[' || s[i] == '{') sta.push(s[i]); else if (sta.empty() == true) return false; else{ if (sta.top() == '(' && s[i] == ')') sta.pop(); else if (sta.top() == '[' && s[i] == ']') sta.pop(); else if (sta.top() == '{' && s[i] == '}') sta.pop(); else return false; } } if (sta.empty() == true) return true; else return false; } int main() { string s1 = "()", s2 = "()[]{}", s3 = "(]", s4 = "([)]", s5 = "{[]}"; cout << isValid(s1) << endl << isValid(s2) << endl << isValid(s3) << endl << isValid(s4) << endl << isValid(s5) << endl; system("pause"); }



