Goal Parser Interpretation

You can solve this problem by iterating through the command string and recognizing the patterns “G”, “()”, and “(al)” and translating them accordingly.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def interpret(self, command: str) -> str:
        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

Explanation

  • Initialize an empty string result to hold the final interpretation.
  • Iterate through the command string using a while loop with an index i.
  • Check for each possible pattern:
    • If the current character is “G”, append “G” to the result.
    • If the current 2 characters are “()”, append “o” to the result.
    • If the current 4 characters are “(al)”, append “al” to the result.
  • Increment the index i accordingly for each pattern (1 for “G”, 2 for “()”, 4 for “(al)”).
  • Return the final result string after the loop.