Goal Parser Interpretation

easy string parsing simulation

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.

Inputcommand = "G()(al)"
Output"Goal"
G → G, () → o, (al) → al, so the result is "Goal".
Inputcommand = "(al)G(al)()()G"
Output"alGalooG"
Each token is replaced independently and the results are joined.

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;
}
Time: O(n) Space: O(n)