摘要:?jiǎn)栴}解答這題是看里面的的代碼如果比大或等的話,就繼續(xù)掃下去否則,我們就找到當(dāng)前有可能刪去的,然后刪掉看新的如果只從左到右掃了,還是的時(shí)候,我們還要再?gòu)挠彝髵咭槐榉駝t兩遍都掃完了,就加入結(jié)果中去
問(wèn)題:
Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
Note: The input string may contain letters other than the parentheses ( and ).
Examples:
"()())()" -> ["()()()", "(())()"]
"(a)())()" -> ["(a)()()", "(a())()"]
")(" -> [""]
解答:
這題是看discuss里面的dietpanda的代碼:
public void remove(String s, Listresult, int last_i, int last_j, char[] par) { for (int stack = 0, i = last_i; i < s.length(); i++) { if (s.charAt(i) == par[0]) stack++; if (s.charAt(i) == par[1]) stack--; //如果"("比")"大或等的話,就繼續(xù)掃下去 if (stack >= 0) continue; //否則,我們就找到當(dāng)前有可能刪去的")",然后刪掉看新的string for (int j = last_j; j <= i; j++) { if (s.charAt(j) == par[1] && (j == last_j || s.charAt(j - 1) != par[1])) { remove(s.substring(0, j) + s.substring(j + 1, s.length()), result, i, j, par); } } return; } String reversed = new StringBuilder(s).reverse().toString(); //如果只從左到右掃了,par[0]還是"("的時(shí)候,我們還要再?gòu)挠彝髵咭槐? if (par[0] == "(") { remove(reversed, result, 0, 0, new char[]{")", "("}); } else { //否則兩遍都掃完了,就加入結(jié)果中去 result.add(reversed); } } public List removeInvalidParentheses(String s) { List result = new ArrayList (); remove(s, result, 0, 0, new char[]{"(", ")"}); return result; }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://m.specialneedsforspecialkids.com/yun/64920.html
摘要:一個(gè)合法的字符串是指左括號(hào)和右括號(hào)必定成對(duì)出現(xiàn)。要求得出用最少次數(shù)的刪除可以得到的所有的合法字符串。最后兩個(gè)結(jié)果重復(fù),因此只保留,兩個(gè)結(jié)果。最終生成的合法字符串為。方法相同于上一種情況。其中出現(xiàn)了兩次。在該下標(biāo)前的刪除將會(huì)產(chǎn)生重復(fù)的結(jié)果。 題目要求 Remove the minimum number of invalid parentheses in order to make the...
Problem Given a string containing only three types of characters: (, ) and *, write a function to check whether this string is valid. We define the validity of a string by these rules: Any left parent...
Problem You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way. The null node needs to be represented by empty parenthesis pair (). And...
摘要:題意從一顆二叉樹(shù)轉(zhuǎn)為帶括號(hào)的字符串。這題是的姊妹題型,該題目的解法在這里解法。 LeetCode 606. Construct String from Binary Tree You need to construct a string consists of parenthesis and integers from a binary tree with the preorder t...
摘要:題意從一個(gè)帶括號(hào)的字符串,構(gòu)建一顆二叉樹(shù)。其中當(dāng)而時(shí),展示為一個(gè)空的括號(hào)。同時(shí)要考慮負(fù)數(shù)的情況,所以在取數(shù)字的時(shí)候,必須注意所在位置。遇到則從棧中出元素。最后中的元素就是,返回棧頂元素即可。 LeetCode 536. Construct Binary Tree from String You need to construct a binary tree from a string ...
閱讀 783·2023-04-25 17:33
閱讀 3637·2021-07-29 14:49
閱讀 2487·2019-08-30 15:53
閱讀 3440·2019-08-29 16:27
閱讀 2008·2019-08-29 16:11
閱讀 1036·2019-08-29 14:17
閱讀 2443·2019-08-29 13:47
閱讀 2023·2019-08-29 13:28