Goal Parser Interpretation(#1678)
Category: String, Foundation
π§© 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"
Input: "G()()()()(al)"
Output: "Gooooal"
Input: "(al)G(al)()()G"
Output: "alGalooG"
π§ Approach
We can solve this problem in two ways:
Approach 1 β Brute Force (Using Loop):**
Iterate through each character in the string. If the character is 'G', append 'G'. If you find '()', append 'o' and skip the next character. If you find '(al)', append 'al' and skip the next 3 characters.
Approach 2 β Optimized (Using replaceAll):**
Use JavaScriptβs `replaceAll()` method to first replace all '()' with 'o' and then replace all '(al)' with 'al'. This makes the code much cleaner and shorter.
π» Code
// πΉ Approach 1: Brute Force (Using Loop)
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;
};
// πΉ Approach 2: Optimized (Using replaceAll)
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.