博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode]Longest Valid Parentheses
阅读量:4150 次
发布时间:2019-05-25

本文共 2204 字,大约阅读时间需要 7 分钟。

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() function		stack
> charStack; vector
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 length int 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 string return 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
charStack; vector
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; }};

转载地址:http://tlxti.baihongyu.com/

你可能感兴趣的文章
laravel事务
查看>>
【JavaScript 教程】浏览器—History 对象
查看>>
这才是学习Vite2的正确姿势!
查看>>
7 个适用于所有前端开发人员的很棒API,你需要了解一下
查看>>
49个在工作中常用且容易遗忘的CSS样式清单整理
查看>>
20种在学习编程的同时也可以在线赚钱的方法
查看>>
隐藏搜索框:CSS 动画正反向序列
查看>>
【视频教程】Javascript ES6 教程27—ES6 构建一个Promise
查看>>
【5分钟代码练习】01—导航栏鼠标悬停效果的实现
查看>>
127个超级实用的JavaScript 代码片段,你千万要收藏好(中)
查看>>
127个超级实用的JavaScript 代码片段,你千万要收藏好(下)
查看>>
【web素材】03-24款后台管理系统网站模板
查看>>
Flex 布局教程:语法篇
查看>>
年薪50万+的90后程序员都经历了什么?
查看>>
2019年哪些外快收入可达到2万以上?
查看>>
【JavaScript 教程】标准库—Date 对象
查看>>
前阿里手淘前端负责人@winter:前端人如何保持竞争力?
查看>>
【JavaScript 教程】面向对象编程——实例对象与 new 命令
查看>>
我在网易做了6年前端,想给求职者4条建议
查看>>
SQL1015N The database is in an inconsistent state. SQLSTATE=55025
查看>>