模拟面试的时候,遇到了这种题
确实是简单至极的题目
但是我
忘了栈用stl怎么写。又懒得用结构体写栈。 自己用vector造了一个栈。。。
我猜压根没像我这么写的
就很快乐
class Solution { public: bool isValid(string s) { if(s == "") return true; vector<char> strs; int len = s.length(); strs.push_back(s[0]) ; int j = 1; for (int i = 1;i< len;i++) { j = strs.size() ; strs.push_back( s[i]) ; if(j>0 ) { if( (strs[j]== ')' && strs[j-1]=='(' ) || (strs[j]== ']' && strs[j-1]=='[') ||(strs[j]== '}' && strs[j-1]=='{')) { strs.pop_back(); strs.pop_back(); } } } if(strs.empty()) return true; else return false; } };
思路2:
直接上asc码,肯定是最快的
class Solution { public: bool isValid(string s) { string tmp = " "; for (int i = 0; i < s.size(); i++) { if (s[i]-tmp.back()==1||s[i]-tmp.back()==2) {//ascll码 tmp.pop_back(); } else { tmp += s[i]; } } return tmp.size() == 1; } };