1 minute read

You own a Goal Parser that can interpret a string command. The command consists of an alphabet of “G”, “()” and/or “(al)” in some order. The Goal Parser will interpret “G” as the string “G”, “()” as the string “o”, and “(al)” as the string “al”. The interpreted strings are then concatenated in the original order.

Given the string command, return the Goal Parser’s interpretation of command.

Example 1:

Input: command = “G()(al)” Output: “Goal” Explanation: The Goal Parser interprets the command as follows: G -> G () -> o (al) -> al The final concatenated result is “Goal”. Example 2:

Input: command = “G()()()()(al)” Output: “Gooooal” Example 3:

Input: command = “(al)G(al)()()G” Output: “alGalooG”

/**
 * @param {string} command
 * @return {string}
 */
var interpret = function (command) {
  let stack = [];

  for (let i = 0; i < command.length; i++) {
    if (command.charAt(i) === "G") {
      stack.push("G");
    } else if (command.charAt(i) === "(") {
      stack.push("(");
    } else if (command.charAt(i) === ")") {
      stack.pop();
      stack.push("o");
    } else if (command.charAt(i) === "a") {
      stack.pop();
      stack.push("al");
      i += 2;
    }
  }
  return stack.join("");
};

let stack = [];: Initialize an empty array stack to act as a stack.

for (let i = 0; i < command.length; i++) {: Start a loop that iterates over each character in the command string.

if (command.charAt(i) === "G") {: Check if the current character is “G”.

stack.push("G"): If the character is “G”, push “G” onto the stack.

} else if (command.charAt(i) === "(") {: Check if the current character is “(“.

stack.push("("): If the character is “(“, push “(“ onto the stack.

} else if (command.charAt(i) === ")") {: Check if the current character is “)”.

stack.pop(): If the character is “)”, pop the last “(“ from the stack.

stack.push("o"): Then, push “o” onto the stack.

} else if (command.charAt(i) === "a") {: Check if the current character is “a”.

stack.pop(): If the character is “a”, pop the last “(“ from the stack.

stack.push("al"): Then, push “al” onto the stack.

i += 2: Increment the loop index by 2 to skip the next two characters (“l”).

return stack.join("");: Return the modified string by joining the elements in the stack into a single string.

Leave a comment