Leetcode Problem 1678: Goal Parser Interpretation
You own a Goal Parser that can interpret a string command. The command consists of an alphabet of “G”, “()”, and/or “(al)” in some order. The Goal Parser will interpret the command as follows:
Given the string command
, return the Goal Parser’s interpretation of the command.
Example:
Input: command = "G()(al)"
Output: "Goal"
Before diving into the code, let’s clarify a few points:
For now, we’ll assume:
command
length is between 1 and 100.command
.def interpret(command: str) -> str:
# Initialize an empty result string
result = ""
i = 0
while i < len(command):
if command[i] == 'G':
result += 'G'
i += 1
elif command[i:i+2] == '()':
result += 'o'
i += 2
elif command[i:i+4] == '(al)':
result += 'al'
i += 4
return result
# Example usage:
print(interpret("G()(al)"))
print(interpret("G()()()()(al)"))
print(interpret("(al)G(al)()()G"))
The time complexity of this solution is O(n), where n
is the length of the input string command
. This is because we are scanning through the string once and processing sections of it in constant time.
The space complexity is also O(n) since we create a new result string whose size could be up to the length of the input string command
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?