Skip to content

Commit 54d589c

Browse files
committed
Adding Efficient Solution for Problem - 1021 - Remove Parantheses
1 parent d71316b commit 54d589c

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
##==================================
2+
## Leetcode
3+
## Student: Vandit Jyotindra Gajjar
4+
## Year: 2020
5+
## Problem: 1021
6+
## Problem Name: Remove Outermost Parantheses
7+
##===================================
8+
#
9+
#A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation. For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings.
10+
#
11+
#A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings.
12+
#
13+
#Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings.
14+
#
15+
#Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S.
16+
#
17+
#Example 1:
18+
#
19+
#Input: "(()())(())"
20+
#Output: "()()()"
21+
#Explanation:
22+
#The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
23+
#After removing outer parentheses of each part, this is "()()" + "()" = "()()()".
24+
#
25+
#Example 2:
26+
#
27+
#Input: "(()())(())(()(()))"
28+
#Output: "()()()()(())"
29+
#Explanation:
30+
#The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))".
31+
#After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())".
32+
#
33+
#Example 3:
34+
#
35+
#Input: "()()"
36+
#Output: ""
37+
#Explanation:
38+
#The input string is "()()", with primitive decomposition "()" + "()".
39+
#After removing outer parentheses of each part, this is "" + "" = "".
40+
class Solution:
41+
def removeOuterParantheses(self, S):
42+
tmp = "" #Initialize tmp empty string
43+
final_S = "" #Initialize final_S empty string which we'll return at the end.
44+
count = 0 #Initialize count
45+
for i in range(len(S)): #Loop through our string
46+
tmp += S[i] #tmp string will be tmp + S[i]. i.e: "" + "(" = "("
47+
if S[i] == '(': #Condition-check: If S[i] == '('
48+
count += 1 #We'll increase our count by 1
49+
else: #Condition-check: else then
50+
count -= 1 #We'll decrease count by 1
51+
if count == 0: #Condition-check: Now, if we reach count to zero.
52+
final_S += tmp[1:-1] #final_S will be final_S + tmp[1:-1]. i.e. = "" + "(()())" = "" + "()()" = "()()"
53+
tmp = "" #Then we'll change previous tmp string to empty string
54+
return final_S #Finally we'll return final_S.

0 commit comments

Comments
 (0)