[LeetCode]1021.RemoveOutermostParentheses(刪除最外層的括號 )

有效括號字符串爲空 ("")、"(" + A + ")" 或 A + B,其中 A 和 B 都是有效的括號字符串,+ 代表字符串的連接。例如,"","()","(())()" 和 "(()(()))" 都是有效的括號字符串。
如果有效字符串 S 非空,且不存在將其拆分爲 S = A+B 的方法,我們稱其爲原語(primitive),其中 A 和 B 都是非空有效括號字符串。
給出一個非空有效字符串 S,考慮將其進行原語化分解,使得:S = P_1 + P_2 + ... + P_k,其中 P_i 是有效括號字符串原語。
對 S 進行原語化分解,刪除分解中每個原語字符串的最外層括號,返回 S 。
 示例 1:
輸入:"(()())(())"
輸出:"()()()"
解釋:
輸入字符串爲 "(()())(())",原語化分解得到 "(()())" + "(())",
刪除每個部分中的最外層括號後得到 "()()" + "()" = "()()()"。
示例 2:
輸入:"(()())(())(()(()))"
輸出:"()()()()(())"
解釋:
輸入字符串爲 "(()())(())(()(()))",原語化分解得到 "(()())" + "(())" + "(()(()))",
刪除每個部分中的最外層括號後得到 "()()" + "()" + "()(())" = "()()()()(())"。
示例 3:

輸入:"()()"
輸出:""
解釋:
輸入字符串爲 "()()",原語化分解得到 "()" + "()",
刪除每個部分中的最外層括號後得到 "" + "" = ""。
 

提示:

S.length <= 10000
S[i] 爲 "(" 或 ")"
S 是一個有效括號字符串

 

 

 

 

 

 

package leetcode.Stack;

import java.util.Stack;

public class Easy_1021RemoveOutermostParentheses {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String S="()()";
		Easy_1021RemoveOutermostParentheses rop=new Easy_1021RemoveOutermostParentheses();
		Solution solution=rop.new Solution();
		solution.removeOuterParentheses(S);
	}

	/*
	 * 我的思路:通過棧分解最外層
	 * 執行用時 :10 ms, 在所有 Java 提交中擊敗了37.53%的用戶
	 * 內存消耗 :39.7 MB, 在所有 Java 提交中擊敗了7.69%的用戶
	 */
	class Solution {
	    public String removeOuterParentheses(String S) {
	    	Stack<Character> stack=new Stack<Character>();
	    	StringBuilder sb=new StringBuilder();
	    	for(char ch:S.toCharArray()){
	    		if(ch=='('&&!stack.isEmpty()){//當不爲第一個左括號時,入棧,加入sb
	    			stack.push(ch);
	    			sb.append(ch);
	    		}else if(stack.isEmpty()){//當爲每個原語字符串的最外層括號時,入棧,不加入sb
	    			stack.push(ch);
	    		}else if(ch==')'){//當爲右括號時,將棧中的左括號出棧,加入sb,如果爲原語字符串的最外層括號,不加入sb
	    			stack.pop();
	    			if(!stack.isEmpty()){//當
	    			sb.append(ch);
	    			}
	    		}
	    	}
	    	System.out.println(sb.toString());
	    	return sb.toString();
	    }
	    /*
	     * 參考思路1:遍歷字符串,遇到左括號就入棧,遇到右括號就出棧,每次棧空的時候,都說明找到了一個原語,記錄下每個原語的起始位置和結束位置,取原字符串在原語的起始位置+1到原語的結束位置的子串便得到原語刪除了最外層括號的字符串,拼接,即可解出答案。
	     */
	    public String removeOuterParentheses1(String S) {
	        int num = 0;
	        int index = 0;
	        StringBuilder sb = new StringBuilder();
	        for(int i = 0;i < S.length();i++){
	            if(S.charAt(i) == '('){
	                num++;
	            }
	            if(S.charAt(i) == ')'){
	                num--;
	            }
	            if(num == 1 && S.charAt(i) == '('){
	                index = i;
	            }
	            if(num == 0){
	                sb.append(S.substring(index + 1,i));
	            }
	        }
	        return sb.toString();
	    }
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章