国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

leecode 解題總結:32 Longest Valid Parentheses

2019-11-10 22:57:35
字體:
來源:轉載
供稿:網友
#include <iostream>#include <stdio.h>#include <vector>#include <string>#include <stack>using namespace std;/*問題:Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.For "(()", the longest valid parentheses substring is "()", which has length = 2.Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.分析:此題相當于在字符串中尋找最長的有效括號對。如果暴力破解:就枚舉任意開始位置,從該起始位置不斷尋找符合有效括號對的字符,時間復雜度應該為O(n^2)更特殊的,可以每次找到"("的位置,從該位置進行計算。也可以從后向前尋找"(",記錄dp[i]表示以A[i]為"("的有效長度,下次找到A[i]前面的一個"("記為A[j],dp[j]={dp[i] + i - j , if A[j]到A[i-1]不是有效括號對      { 0 ,if A[j]到A[i-1]不是有效括號對初始化:對任意,dp[i]=0一旦發現dp[j]=0,返回dp[i]輸入:(())()())()(())輸出:246報錯:Input:"()(())"Output:2Expected:6錯在了并沒有考慮(())這種嵌套情況,需要:羅列每個起始字符關鍵:1 //string.find(string s , int pos ,int n):pos表示從后向前查找的首個字符的位置,n表示查找字符串s的前面n個字符作為查找int index = s.rfind("(" , len);//rfind用于子串查找,find_last_of用于字符匹配2 另外一種解法是:凡是沒有遇到:棧頂為"(",且當前字符為")"的情況,就壓入當前字符到棧中;  否則,表示找到了一種匹配,則彈出棧頂元素,則此時棧頂對應的是不匹配的元素下標,那么匹配的長度  就是當前字符的下標-棧頂下標。  注意之所以初始時壓入:-1,是為了"()"這種情況的時候,確保棧頂一定會存在一個元素*/class Solution {public:    int longestValidParentheses(string s) {if(s.empty()){return 0;}int len = s.length();stack<int> stackInt;stackInt.push(-1);//防止計算有效長度時棧為空異常int maxLen = 0;for(int i = 0 ; i < len ;i++){int index = stackInt.top();if(index != -1 && s[i] == ')' && s[index] == '('){stackInt.pop();maxLen = max(maxLen , i - stackInt.top());//這里有效長度=當前下標-棧頂對應下標(最后一個不匹配的下標)}else{stackInt.push(i);}}return maxLen;}};void PRocess(){string str;while(cin >> str){Solution solution;int result = solution.longestValidParentheses(str);cout << result << endl;}}int main(int argc , char* argv[]){//test();process();getchar();return 0;}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 佳木斯市| 新河县| 堆龙德庆县| 镇安县| 漳平市| 萍乡市| 河东区| 上栗县| 郑州市| 兴宁市| 都江堰市| 湘乡市| 沂南县| 博爱县| 广丰县| 高清| 大洼县| 博客| 上饶县| 浪卡子县| 西充县| 高台县| 陵川县| 桦川县| 亚东县| 平定县| 文水县| 唐海县| 南汇区| 五常市| 伊春市| 白玉县| 津市市| 吉林市| 剑河县| 台北市| 双江| 宜都市| 龙山县| 松江区| 汉沽区|