Goal Parser Interpretation
Problem
A command string is made of the tokens "G", "()", and "(al)" in some order. The Goal Parser reads "G" as "G", "()" as "o", and "(al)" as "al", then concatenates the interpreted pieces in their original order. Return the parser's interpretation of the command.
command = "G()(al)""Goal"command = "(al)G(al)()()G""alGalooG"def interpret(command):
res = []
i = 0
n = len(command)
while i < n:
if command[i] == 'G':
res.append('G')
i += 1
elif command[i + 1] == ')':
res.append('o')
i += 2
else:
res.append('al')
i += 4
return ''.join(res)
function interpret(command) {
let res = "";
let i = 0;
const n = command.length;
while (i < n) {
if (command[i] === 'G') {
res += 'G';
i += 1;
} else if (command[i + 1] === ')') {
res += 'o';
i += 2;
} else {
res += 'al';
i += 4;
}
}
return res;
}
String interpret(String command) {
StringBuilder res = new StringBuilder();
int i = 0, n = command.length();
while (i < n) {
if (command.charAt(i) == 'G') {
res.append('G');
i += 1;
} else if (command.charAt(i + 1) == ')') {
res.append('o');
i += 2;
} else {
res.append("al");
i += 4;
}
}
return res.toString();
}
string interpret(string command) {
string res;
int i = 0, n = command.size();
while (i < n) {
if (command[i] == 'G') {
res += 'G';
i += 1;
} else if (command[i + 1] == ')') {
res += 'o';
i += 2;
} else {
res += "al";
i += 4;
}
}
return res;
}
Explanation
Every token in the command is self-identifying from its first character, so a single left-to-right scan with one index i is enough — no backtracking and no nested parsing.
If command[i] is 'G', the token is just "G": append 'G' and advance by 1.
Otherwise command[i] is '(', and the next character decides the token. If command[i + 1] is ')' we have "()" → append 'o' and jump past 2 characters. Otherwise it must be "(al)" → append "al" and jump past 4 characters.
Because the constraints promise the string is built only from these three tokens, those three cases are exhaustive; we never read out of bounds and each token is consumed exactly once.
Appending to a list / StringBuilder and joining at the end keeps the work linear. With input "G()(al)" the scan emits G, then o, then al, producing "Goal".