日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

[Leetcode] Longest Valid Parentheses

發布時間:2023/11/29 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [Leetcode] Longest Valid Parentheses 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

找出字串裡最長的合法括號組

簡單說,一樣stack搜尋合法parenth,把不合法的 ( & ) index 紀錄下來,最後算index間的差值取最大就是最長的

?

public class Solution{/// <summary>/// 把不合法的'(' ')'的index記下來,取最長的差值就是/// </summary>/// <param name="s"></param>/// <returns></returns>public int LongestValidParentheses(string s){char[] aaa = s.ToCharArray();int aaaLength = aaa.Length;s = null;//有剩下的'('就是不合法的Stack<int> notLeftMatched = new Stack<int>();//不合法的')'List<int> notMatched = new List<int>();int tempCount = 0;int resultCount = 0;int popCount = 0;int j = 0;for (int i = 0; i < aaa.Length; i++){j = i;if (aaa[i] == '('){//存的是1為base的indexnotLeftMatched.Push(++j);}else if (aaa[i] == ')' ){//有'('可以配對if(notLeftMatched.Count > 0){notLeftMatched.Pop();popCount++;}else{//沒有就表示是個斷點')' 記下來notMatched.Add(++j);}}}int[] all = new int[notLeftMatched.Count + notMatched.Count];notMatched.CopyTo(all);notLeftMatched.CopyTo(all, notMatched.Count);//不合法的'(' ')'組成一個陣列後排序all = all.OrderBy(x => x).ToArray();notLeftMatched = null;notMatched = null;aaa = null;int afterIndex = aaaLength;///算斷點間的差值if (all.Length > 0 && popCount > 0){for (int i = all.Length - 1; i >= 0; i--){//取得最後一個if(i == all.Length - 1){afterIndex = all[i];continue;}//不包含自已 再扣1//例如在1跟4之間合法的就只有2 3 所以是 4 -1 -1tempCount = afterIndex - all[i] -1;if (tempCount > resultCount){resultCount = tempCount;}afterIndex = all[i];}//算第一個斷點跟最後一個斷點跟字元陣列頭尾的差值//例如長10 斷點是 2 5 7 那還有7-10 , 1-2之間的長度要算//算尾tempCount = aaaLength - all[all.Length -1];if (tempCount > resultCount){resultCount = tempCount;}//算頭tempCount = all[0] - 1;if (tempCount > resultCount){resultCount = tempCount;}}else{resultCount = popCount * 2;}all = null;return resultCount;}}

?

轉載于:https://www.cnblogs.com/seako/p/10674574.html

總結

以上是生活随笔為你收集整理的[Leetcode] Longest Valid Parentheses的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。