Goal Parser Interpretation (LeetCode 1678): A Tiny Tokenizer
Problem. A string command is made of the tokens G, () and (al). The parser reads G as "G", () as "o" and (al) as "al". Return the interpreted string.
Approach 1: chained replace
def interpret(command):
return command.replace("()", "o").replace("(al)", "al")
The order matters a little: replacing () first is safe because (al) never contains (). This is fine in most languages, but each replace makes a new string.
Approach 2: single pass
Treat it like a mini tokenizer. Look at the current character and decide how many characters to consume.
def interpret(command):
out = []
i = 0
while i < len(command):
if command[i] == "G":
out.append("G")
i += 1
elif command[i + 1] == ")":
out.append("o")
i += 2
else:
out.append("al")
i += 4
return "".join(out)
Time is O(n) and the output buffer is the only extra space.
Why interviewers ask this
It is an easy problem, so the signal is in how you talk: do you state the token set, explain why peeking at command[i + 1] is safe (the input is guaranteed valid), and pick a list-and-join over repeated string concatenation? Those habits carry over to harder parsing questions like Decode String.
For timed online assessments, practice matters more than memorizing tricks. Linkjob AI offers AI help for online coding assessments if you want hints while you practice. (Disclosure: I work on Linkjob AI.)
Further reading: Linkjob AI resource directory
评论
发表评论