Goal Parser Interpretation
(#1678), Easy
Category: String
Problem Statement
You are given a string `command`. The command string follows this format: - 'G' stands for the character G - '()' stands for the character o - '(al)' stands for the string 'al' Your task is to return the Goal Parser's interpretation of the command string.
Examples
Input: "G()(al)"
Output: "Goal"
Explanation: 'G' remains 'G', '()' becomes 'o', and '(al)' becomes 'al'.
Input: "G()()()()(al)"
Output: "Gooooal"
Explanation: Multiple '()' become multiple 'o', followed by '(al)' → 'al'.
Input: "(al)G(al)()()G"
Output: "alGalooG"
Explanation: Each '(al)' → 'al', '()' → 'o', and 'G' remains 'G'.
Approach
Brute Force (Using Loop)
- Initialize an empty string `str`.
- Iterate through each character in the `command` string.
- If the character is `'G'`, append `'G'` to `str`.
- If you encounter `'('` and the next character is `')'`, append `'o'` to `str` and increment `i` by 1 to skip `')'`.
- Otherwise, append `'al'` to `str` and increment `i` by 3 to skip the full '(al)'.
- Return the final string `str`.
var interpret = function(command) {
let str = "";
for (let i = 0; i < command.length; i++) {
if (command[i] === "G") {
str += "G";
} else if (command[i] === "(" && command[i + 1] === ")") {
str += "o";
i++;
} else {
str += "al";
i += 3;
}
}
return str;
};
Optimized (Using replaceAll)
- Use `replaceAll()` method on the string to first replace all occurrences of `'()'` with `'o'`.
- Then replace all occurrences of `'(al)'` with `'al'`.
- Return the final modified string.
var interpret = function(command) {
let str = command.replaceAll("()", "o");
return str.replaceAll("(al)", "al");
};
Complexity
Time: O(n), where n is the length of the input string.
Space: O(n), for the newly created interpreted string.