[LeetCode]Longest Valid Parentheses
来源:互联网 发布:ios11 数据流量开关 编辑:程序博客网 时间:2024/05/02 04:23
class Solution {//once meet Parentheses, we should think of stack//then it is some thing trivialpublic:int longestValidParentheses(string s) {// Start typing your C/C++ solution below// DO NOT write int main() functionstack<pair<char, int>> charStack;vector<bool> valid(s.size(), false);for (int i = 0; i < s.size(); ++i){if ( !charStack.empty() ){char topChar = charStack.top().first;int topPos = charStack.top().second;if( topChar == '(' && s[i] == ')'){charStack.pop();for (int j = topPos; j <= i; ++j)valid[j] = true;}else charStack.push(make_pair(s[i], i));}else charStack.push(make_pair(s[i], i));}//then count the longest lengthint nowLen = 0;int maxLen = 0;for (int i = 0; i < s.size(); ++i){if(valid[i])nowLen++;else {maxLen = max(maxLen, nowLen);nowLen = 0;}}maxLen = max(maxLen, nowLen);//note here, then end of the stringreturn maxLen;}};
second time
class Solution {//DP based solution need O(n^3)//stack based solution need O(n^2)public: struct Node { char c; int pos; Node(char _c, int _pos):c(_c),pos(_pos){}; }; int longestValidParentheses(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function stack<Node> charStack; vector<int> pLen(s.size(), 0); for(int i = 0; i < s.size(); ++i) { if(s[i] == '(') charStack.push(Node(s[i], i)); else { if(!charStack.empty() && charStack.top().c == '(') { int pos = charStack.top().pos; pLen[pos] = i-pos+1; charStack.pop(); } else charStack.push(Node(s[i], i)); } } //get maxlen int maxLen = 0; for(int i = 0; i < s.size(); ++i) { int curLen = 0; int nextPos = i; while(nextPos < s.size() && pLen[nextPos] != 0) { curLen += pLen[nextPos]; nextPos = pLen[nextPos]+nextPos; } maxLen = max(maxLen, curLen); } return maxLen; }};
- LeetCode: Longest Valid Parentheses
- LeetCode Longest Valid Parentheses
- LeetCode: Longest Valid Parentheses
- [Leetcode] Longest Valid Parentheses
- [leetcode]longest Valid Parentheses(!!)
- [Leetcode] Longest Valid Parentheses
- leetcode Longest Valid Parentheses
- 【leetcode】Longest Valid Parentheses
- [LeetCode]Longest Valid Parentheses
- [leetcode] Longest Valid Parentheses
- LeetCode-Longest Valid Parentheses
- [LeetCode] Longest Valid Parentheses
- LeetCode:Longest Valid Parentheses
- Leetcode: Longest Valid Parentheses
- Leetcode:Longest Valid Parentheses
- leetcode Longest Valid Parentheses
- leetcode Longest Valid Parentheses
- LeetCode Longest Valid Parentheses
- 直接拿来用!最火的Android开源项目(一)
- [LeetCode]Longest Substring Without Repeating Characters
- 线性代数 3d 坐标和矩阵
- java-hibernate 人生第一配(2个xml加使用)
- Combobox控件的应用
- [LeetCode]Longest Valid Parentheses
- 直接拿来用!最火的Android开源项目(二)
- ps命令用法
- C++五种类型的迭代器
- [LeetCode]Maximal Rectangle
- 土豆、优酷、酷6、搜狐、音悦台等在线视频网站视频下载方法
- http 错误 404.3 not found
- 启用 Tomcat 下的 HTTPS/java 证书签证
- 收集的一些查询阻塞和锁的SQL,非常好用