題目說明:給你一組括號字串,要你移除掉最外部的括號,由於詳細的題目敘述實在太長,這邊直接省略。
Case 1
Input: s = "(()())(())"
Output: "()()()"
Explanation:
The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
After removing outer parentheses of each part, this is "()()" + "()" = "()()()".
Case 2:
Input: s = "(()())(())(()(()))"
Output: "()()()()(())"
Explanation:
The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))".
After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())".
Case 3:
Input: s = "()()"
Output: ""
Explanation:
The input string is "()()", with primitive decomposition "()" + "()".
After removing outer parentheses of each part, this is "" + "" = "".
解題思路:這題同樣是使用stack,將左括號push,遇到右括號要pop。但是在結果的呈現上因為最外部的括號省略,因此我們要先判斷當前stack的size是否大於0,大於0才要需要將左括號加進去結果裡面,如果等於0就代表是最外部的括號;說了這麼多可能有些聽起來還是有聽沒有懂,因此直接用例子來進行說明或許變得簡單明瞭。
(()())這組字串當中,一開始遇到左括號,stack要push進去,但是在結果顯示上我們不需要這個括號因為它是最外部的括號。因此在push到stack之前我們要先考慮到這個stack的size是否>0,進而進行判斷是否為最外部的括號。同時對於右括號結果上的處理也是同樣的邏輯,步驟如下:
Step Stack Result
0 ( ""
1 (( "("
2 ( "()"
3 (( "()("
4 ( "()()"
5 empty "()()"
附上程式碼和註解
Java
class Solution {
public String removeOuterParentheses(String s) {
Stack<Character>st=new Stack<>();
StringBuilder sb=new StringBuilder();
for(int i=0;i<s.length();i++)
{
char ch=s.charAt(i);
if(ch=='(')
{
if(st.size()>0)
{
sb.append(ch);
}
st.push(ch);
}else
{
st.pop();
if(st.size()>0)
{
sb.append(ch);
}
}
}
return sb.toString();
}
}
Python
class Solution:
def removeOuterParentheses(self, s: str) -> str:
res=''
stack=[]
for i in s:
if i=='(':
if len(stack)>0:
res+=i
stack.append(i)
else:
stack.pop()
if len(stack)>0:
res+=i
return res