Leetcode 1678. Goal Parser Interpretation
You are given a string command
that consists of “G”, “()” and/or “(al)” in some order. The goal is to interpret this string where:
Return the interpreted string.
Input: command = "G()(al)"
Output: "Goal"
Input: command = "G()()()()(al)"
Output: "Gooooal"
Input: command = "(al)G(al)()()G"
Output: "alGalooG"
command
string?
1
and 100
.command
string.#include <iostream>
#include <string>
class Solution {
public:
std::string interpret(std::string command) {
std::string result;
for (int i = 0; i < command.length(); ++i) {
if (command[i] == 'G') {
result += 'G';
} else if (command[i] == '(' && command[i + 1] == ')') {
result += 'o';
i++; // Skip the next character
} else if (command[i] == '(' && command[i + 1] == 'a') {
result += "al";
i += 3; // Skip the next three characters, i.e., "al)"
}
}
return result;
}
};
int main() {
Solution solution;
std::string command1 = "G()(al)";
std::string command2 = "G()()()()(al)";
std::string command3 = "(al)G(al)()()G";
std::cout << solution.interpret(command1) << std::endl; // Output: "Goal"
std::cout << solution.interpret(command2) << std::endl; // Output: "Gooooal"
std::cout << solution.interpret(command3) << std::endl; // Output: "alGalooG"
return 0;
}
This solution efficiently parses and translates the given command string while maintaining a linear time complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?