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

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

leecode 解題總結(jié):32 Longest Valid Parentheses

2019-11-10 19:25:35
字體:
供稿:網(wǎng)友
#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.分析:此題相當(dāng)于在字符串中尋找最長的有效括號對。如果暴力破解:就枚舉任意開始位置,從該起始位置不斷尋找符合有效括號對的字符,時間復(fù)雜度應(yīng)該為O(n^2)更特殊的,可以每次找到"("的位置,從該位置進(jìn)行計(jì)算。也可以從后向前尋找"(",記錄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一旦發(fā)現(xiàn)dp[j]=0,返回dp[i]輸入:(())()())()(())輸出:246報(bào)錯:Input:"()(())"Output:2Expected:6錯在了并沒有考慮(())這種嵌套情況,需要:羅列每個起始字符關(guān)鍵:1 //string.find(string s , int pos ,int n):pos表示從后向前查找的首個字符的位置,n表示查找字符串s的前面n個字符作為查找int index = s.rfind("(" , len);//rfind用于子串查找,find_last_of用于字符匹配2 另外一種解法是:凡是沒有遇到:棧頂為"(",且當(dāng)前字符為")"的情況,就壓入當(dāng)前字符到棧中;  否則,表示找到了一種匹配,則彈出棧頂元素,則此時棧頂對應(yīng)的是不匹配的元素下標(biāo),那么匹配的長度  就是當(dāng)前字符的下標(biāo)-棧頂下標(biāo)。  注意之所以初始時壓入:-1,是為了"()"這種情況的時候,確保棧頂一定會存在一個元素*/class Solution {public:    int longestValidParentheses(string s) {if(s.empty()){return 0;}int len = s.length();stack<int> stackInt;stackInt.push(-1);//防止計(jì)算有效長度時棧為空異常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());//這里有效長度=當(dāng)前下標(biāo)-棧頂對應(yīng)下標(biāo)(最后一個不匹配的下標(biāo))}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;}
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 青川县| 景宁| 荆州市| 五莲县| 耒阳市| 陆丰市| 湾仔区| 舒兰市| 博爱县| 泸西县| 安丘市| 泗水县| 巴楚县| 修武县| 西昌市| 东方市| 张家川| 昌乐县| 五莲县| 增城市| 山阳县| 蚌埠市| 章丘市| 如东县| 松溪县| 黎城县| 莆田市| 梁山县| 大关县| 房产| 武夷山市| 巴楚县| 安康市| 隆尧县| 通河县| 鄂温| 图们市| 松潘县| 河间市| 阿图什市| 凯里市|