leetcode678+括號匹配,stack使用掌握規
阿新 • • 發佈:2018-11-01
https://leetcode.com/problems/valid-parenthesis-string/description/
class Solution { public: bool checkValidString(string s) { stack<int> left, star; for(int i=0; i<s.size(); i++){ if(s[i]=='*') star.push(i); else if(s[i]=='(') left.push(i); else{ // ) if(left.empty()&&star.empty()) return false; if(!left.empty()) left.pop(); else star.pop(); } } while(!left.empty()&&!star.empty()){ if(left.top() > star.top()) return false; // *( 是不行的 left.pop(); star.pop(); } return left.empty(); // star 可以為empty string } };