1678. Goal Parser Interpretation
UnknownView on LeetCode
Time: O(n)
Space: O(n)
Problem Overview
The goal parser maps fixed tokens to output characters: G stays G, () becomes o, (al) becomes al, and ()!
Advertisement
Intuition
The goal parser maps fixed tokens to output characters: G stays G, () becomes o, (al) becomes al, and ()! becomes !. Scan left to right and match the longest pattern first so (al) is not mistaken for ().
Algorithm
- 1Initialize empty result and index i = 0.
- 2While i < length: if s[i] == G, append G and i++.
- 3Else if s starts with "(al)" at i, append "al", i += 4.
- 4Else if s starts with "()" at i, check next char for !.
- 5If "()!", append ! and i += 4; else append o and i += 2.
- 6Return result string.
Example Walkthrough
Input: command = "G()(al)"
- 1.G -> G. () -> o. (al) -> al.
Output: "Goal"
Common Pitfalls
- •Match "(al)" before bare "()" — order of pattern checks matters.
- •Input is guaranteed valid — no error handling needed.
- •StringBuilder avoids repeated string concatenation in loops.
1678.cs
C#
// Approach: Scan the command string; 'G'→'G', '()'→'o', '(al)'→'al'.
// Time: O(n) Space: O(n)
public class Solution
{
public string Interpret(string command)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < command.Length;)
{
if (command[i] == 'G')
{
sb.Append("G");
++i;
}
else if (command[i + 1] == ')')
{
sb.Append("o");
i += 2;
}
else
{
sb.Append("al");
i += 4;
}
}
return sb.ToString();
}
}Advertisement
Was this solution helpful?