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

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

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

2019-11-10 20:19:16
字體:
供稿:網(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.分析:此題相當于在字符串中尋找最長的有效括號對。如果暴力破解:就枚舉任意開始位置,從該起始位置不斷尋找符合有效括號對的字符,時間復雜度應(yīng)該為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一旦發(fā)現(xiàn)dp[j]=0,返回dp[i]輸入:(())()())()(())輸出:246報錯: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 另外一種解法是:凡是沒有遇到:棧頂為"(",且當前字符為")"的情況,就壓入當前字符到棧中;  否則,表示找到了一種匹配,則彈出棧頂元素,則此時棧頂對應(yīng)的是不匹配的元素下標,那么匹配的長度  就是當前字符的下標-棧頂下標。  注意之所以初始時壓入:-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());//這里有效長度=當前下標-棧頂對應(yīng)下標(最后一個不匹配的下標)}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ā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 铁岭县| 云安县| 偃师市| 东乡县| 铜川市| 读书| 道真| 宝应县| 合水县| 明光市| 绥中县| 达日县| 随州市| 仙游县| 玉门市| 从化市| 海晏县| 德保县| 江山市| 阿图什市| 仁寿县| 晋江市| 原阳县| 阳泉市| 厦门市| 霍山县| 开阳县| 木里| 井陉县| 浑源县| 云龙县| 陆良县| 红原县| 阳朔县| 黑山县| 工布江达县| 德兴市| 平邑县| 涟源市| 元谋县| 文山县|