moving on from question 856

This commit is contained in:
Jacob Delgado 2023-07-23 17:58:51 -07:00
parent d25d1f862c
commit 51a53ef6a2
2 changed files with 47 additions and 14 deletions

View File

@ -3,19 +3,51 @@ def scoreOfParentheses(s):
:type s: str
:rtype: int
"""
score = left = right = 0
# Attempted Solution
# score = left = right = 0
for x in s:
if x == "(":
left += 1
score += 1
elif x == ")":
right += 1
score += 1
if left > right:
score = 2 * left
# for x in s:
# if x == "(":
# left += 1
# score += 1
# elif x == ")":
# right += 1
# score += 1
# if (left + right) % 2 == 0:
# score /= 2
# return score
# 96% faster solution
# Initialize an empty list 'a', the length of the input string 's' as 'n'
a, n = [], len(s)
# Initialize 'c' and 't' to 0.
c = t = 0
# Loop through the characters of the input string, starting from the second character (index 1).
for i in range(1, n):
print(f'c is {c}')
print(t)
# If the current character is an opening parenthesis '('
if s[i] == '(':
# Increment the temporary variable 't' to keep track of the depth of nesting.
t += 1
# If the current character is a closing parenthesis ')', and the previous character was an opening parenthesis '('
elif s[i - 1] == '(':
# Calculate the score for the current balanced pair of parentheses and add it to 'c'.
# The score is 2 raised to the power of 't' (2^t).
c += 1 << t
# Decrease the temporary variable 't' as the current nested pair is closed.
t -= 1
else:
score /= 2
return score
# If the current character is a closing parenthesis ')' and the previous character was also a closing parenthesis ')',
# simply decrease the temporary variable 't' to indicate the decrease in the depth of nesting.
t -= 1
print(scoreOfParentheses("()"))
# Return the total score of the balanced parentheses expression, stored in 'c'.
return c
# print(scoreOfParentheses("()")) # 1
print(scoreOfParentheses("(()(()))")) # 6
# print(scoreOfParentheses("()()()")) # 3

View File

@ -1,5 +1,6 @@
# Questions that required help to solve
## Strings
### [22_Generate_Parenthesis](https://leetcode.com/problems/generate-parentheses/description/)
###[856_Score_of_Parenthesis](https://leetcode.com/problems/score-of-parentheses/description/)
## Two Pointers
###