1. 程式人生 > >leetcode 括號匹配系列

leetcode 括號匹配系列

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.

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

感覺這個題是需要一些技巧的,用一個棧記錄左括號的位置,並且用一個變數last記錄上一次匹配失敗的位置。初始化last為-1,然後往後順序遍歷

括號序列,如果碰到左括號則壓棧,如果是右括號則看棧是否空,如果空,則說明這個右括號是個野括號,那麼更新last變數,如果當前棧非空,那麼

說明有左括號可以匹配,則彈出一個,再判斷當前棧是否為空,如果為空,則說明從last到當前位置是全部可以匹配的,所以更新長度i-last,如果

出棧之後發現棧非空,則說明從last到當前位置這段序列,左括號要多於右括號,至於棧裡的這個左括號是否能在之後的序列中匹配是無法預知的,所以

暫時更新長度為i-stack.top()。

上程式碼

class Solution {
public:
    int longestValidParentheses(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
	    int len = s.length();
		if(0 == len) return 0;
		int maxlen = 0,last = -1;
		stack<int> lefts;//stack of left parentheses
		for(int i = 0; i < len; ++i)
		{
			if(s[i] == '(')
				lefts.push(i);
			else if(lefts.empty())
				last = i;
			else
			{
				lefts.pop();
				if(lefts.empty())
					maxlen = max(maxlen,i-last);
				else
					maxlen = max(maxlen,i-lefts.top());
			}
		}
		return maxlen;
    }
};


相關推薦

leetcode 括號匹配系列

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. For "(()", the lon

NYOJ 括號匹配系列2,5

之前被這個題目難住,現在看動態規劃就順便過來AC了它。結果發現當年被難住一點也不丟人。。 括號匹配一很簡單,就是棧的應用,AC程式碼: //=============================================================

括號匹配問題[leetcode]

code 所有 -- for let else ret lee turn 此解法用JavaScript寫的,然後運行速度在leetcode上秒殺所有人,是迄今為止JavaScript上最快的解法 哈哈哈 很開心~~~ /** * @param {string} s *

LeetCode--020--括號匹配

是否有效 exce 判斷 app bool elf stack 剔除 turn 題目描述: 給定一個只包括 ‘(‘,‘)‘,‘{‘,‘}‘,‘[‘,‘]‘ 的字符串,判斷字符串是否有效。 有效字符串需滿足: 左括號必須用相同類型的右括號閉合。 左括號必須以正確的順序閉合。

LeetCode 32 括號匹配

nth 入棧 ati bstr () return -- ava class [LeetCode 32] Longest Valid Parentheses 題目 Given a string containing just the characters ‘(‘ and ‘

leetcode 20 簡單括號匹配(C++和python實現)

【題目描述】 給定一個只包括 '(',')','{','}','[',']' 的字串,判斷字串是否有效。 有效字串需滿足: 左括號必須用相同型別的右括號閉合。 左括號必須以正確的順序閉合。 注意空字串可被認為是有效字串。

leetcode-20:Valid Parentheses有效的括號括號匹配

題目: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the

LeetCode-20、22:Valid、Generate Parentheses(括號匹配、生成)

題目20:Valid Parentheses Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input strin

LeetCode 20 Valid Parentheses(用棧判斷括號匹配

Given a string containing just the characters'(',')','{','}','['and']', determine if the input str

LeetCode第20題 左右括號匹配

第一次提交成功程式碼: import java.util.Stack; public class Solution { public boolean isValid(String s) { Stack<Character> mystack=new Stack&

LeetCode 堆疊佇列 —— 括號匹配(20、232、155)

1. 堆疊(stack) 20,20. Valid Parentheses,括號匹配,堆疊(python 中使用 list 即可實現表示堆疊,list.append:入棧,list.pop():出棧

LeetCode 20. Valid Parentheses 無效的括號匹配 Java易於理解的解法

題目 Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid. 給定一個只包含

LeetCode 20. Valid Parentheses】(合法括號匹配判斷,棧的應用)

題目連結 Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid. An in

leetcode括號匹配問題

題意很簡單,就是給定一系列的(){}[]括號的字串,讓程式檢測出括號是否一一對應,比如({)}這樣的就是不合格的。 思路還是很簡單,就用棧來解決,後進先出,看新的}])元素,是否和棧頂的({[元素匹配。 記錄一下自己失誤的地方,一個是設定棧的元素型別時,忘了可以直接用string::value_

括號匹配演算法(leetcode 20題)

題目:給定一個只包括 '(',')','{','}','[',']' 的字串,判斷字串是否有效。 首先進行對題目進行分析。 1.因為是無規則的括號字元組成一串無規則的括號字串。這裡可以確認使用字串String和字元char 2.明確使用String,char之後,我們如

imooc數據結構探險-棧篇 棧應用括號匹配二 由群友啟發改良james_yuan老師算法

false blog default img pstack 一個 alt 是否 logs 如圖所示 引用群友內容 //老師代碼有點麻煩了,不用聲明兩個mystack的,直接判斷是否是左括號, //是的話就在mystack中push另一半括號;如果是右括號且又不是需要

POJ 2955 Brackets (區間dp 括號匹配)

total con cpp class pre following roc put inpu Brackets Time Limit: 1000MS Memory Limit: 65536K Total Submissio

括號匹配問題

nbsp 字符 match color dbf 防止 lose src false 問題:假設一個算術表達式中可以包含三種括號:圓括號"(" 和")",方括號"["和"]"和花括號"{"和"}",且這三種括號可按任意的次序嵌套使用(如:…[…{…}…[…]…]…[…]…(…

NYOJ15括號匹配

splay 長度 有一個 def can main nyist 一次 5% NYOJ15括號匹配 括號匹配(二) 時間限制:1000 ms | 內存限制:65535 KB 難度:6 描述給你一個字符串,裏面只包含"(",")","[","]"四種符號,請問你需要

POJ2955BRACKETS(區間DP括號匹配

ongl unity jvm wss lfa 匹配 區間 ack .com %E7%94%A8UNITY5%E5%BC%80%E5%8F%91%E7%AC%AC%E4%B8%80%E4%B8%AA%E6%89%8B%E6%9C%BA%E6%B8%B8%E6%88%8F%28