Back to Leetcode Go

1678. Goal Parser Interpretation

website/content.en/ChapterFour/1600~1699/1678.Goal-Parser-Interpretation.md

1.7.971.9 KB
Original Source

1678. Goal Parser Interpretation

Problem

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 "G" as the string "G""()" as the string "o", and "(al)" as the string "al". The interpreted strings are then concatenated in the original order.

Given the string command, return the Goal Parser's interpretation of command.

Example 1:

Input: command = "G()(al)"
Output: "Goal"
Explanation: The Goal Parser interprets the command as follows:
G -> G
() -> o
(al) -> al
The final concatenated result is "Goal".

Example 2:

Input: command = "G()()()()(al)"
Output: "Gooooal"

Example 3:

Input: command = "(al)G(al)()()G"
Output: "alGalooG"

Constraints:

  • 1 <= command.length <= 100
  • command consists of "G""()", and/or "(al)" in some order.

Problem Summary

Please design a Goal Parser that can interpret the string command. command consists of "G", "()", and/or "(al)" in some order. The Goal Parser will interpret "G" as the string "G", "()" as the string "o", and "(al)" as the string "al". Then, concatenate the interpreted strings in their original order. Given the string command, return the Goal Parser's interpretation of command.

Solution Ideas

  • This is an easy problem; just modify the string according to the problem statement. Since it is an easy problem, there is no need to consider nested cases.

Code

go
package leetcode

func interpret(command string) string {
	if command == "" {
		return ""
	}
	res := ""
	for i := 0; i < len(command); i++ {
		if command[i] == 'G' {
			res += "G"
		} else {
			if command[i] == '(' && command[i+1] == 'a' {
				res += "al"
				i += 3
			} else {
				res += "o"
				i ++
			}
		}
	}
	return res
}