From 51a53ef6a292b25e2ab0fbeebe3a61d805108bf6 Mon Sep 17 00:00:00 2001 From: ImAlpha Date: Sun, 23 Jul 2023 17:58:51 -0700 Subject: [PATCH] moving on from question 856 --- Top150Interview/856_Score_of_Parenthesis.py | 60 ++++++++++++++++----- Top150Interview/Questions_to_revisit.md | 1 + 2 files changed, 47 insertions(+), 14 deletions(-) diff --git a/Top150Interview/856_Score_of_Parenthesis.py b/Top150Interview/856_Score_of_Parenthesis.py index 6cb322a..d0e36a8 100644 --- a/Top150Interview/856_Score_of_Parenthesis.py +++ b/Top150Interview/856_Score_of_Parenthesis.py @@ -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 - else: - score /= 2 - return score + # 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 -print(scoreOfParentheses("()")) + # 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: + # 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 + + # Return the total score of the balanced parentheses expression, stored in 'c'. + return c + +# print(scoreOfParentheses("()")) # 1 +print(scoreOfParentheses("(()(()))")) # 6 +# print(scoreOfParentheses("()()()")) # 3 diff --git a/Top150Interview/Questions_to_revisit.md b/Top150Interview/Questions_to_revisit.md index 5236fe4..3004e6e 100644 --- a/Top150Interview/Questions_to_revisit.md +++ b/Top150Interview/Questions_to_revisit.md @@ -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 ### \ No newline at end of file