为了在运行中避免可能出现的危险,即当string emuStack为空,emuStack.begin()和emuStack.end()是什么。采取的策略是先将emuStack重置为非空,再进行其他操作,这样就永远不可能碰到底部。
#include<iostream> #include<string> using namespace std; class Solution { public: bool isValid(string s) { if(s.size() == 0) return true; string emuStack = "s"; string::iterator iter1 = s.begin(); string::iterator iter2 = emuStack.begin(); for(; iter1 != s.end(); iter1++) { if(*iter1 == '}') { if(*iter2 == '{') { emuStack.erase(iter2); iter2 = emuStack.end() - 1; continue; } } if(*iter1 == ']') { if(*iter2 == '[') { emuStack.erase(iter2); iter2 = emuStack.end() - 1; continue; } } if(*iter1 == ')') { if(*iter2 == '(') { emuStack.erase(iter2); iter2 = emuStack.end() - 1; continue; } } if((*iter1 == '{') || (*iter1 == '}') || (*iter1 == '[') || (*iter1 == ']') || (*iter1 == '(') || (*iter1 == ')')) { emuStack += *iter1; iter2 = emuStack.end() - 1; } } //cout << emuStack << endl; if(emuStack.size() == 1) //cout << "valid" << endl; return true; else //cout << "no valid" << endl; return false; //getchar(); //return 1; } }; int main() { //string s = "a{b[c(d)e]f}g"; string s = "]"; Solution solution; cout << solution.isValid(s) << endl; getchar(); return 1; }
原文地址:http://blog.csdn.net/guanzhongshan/article/details/46381863