Rich Text Tokens
FigmaOnsiteMedium
A rich-text editor stores a document as a flat stream of tokens and rebuilds its nesting when it loads the document. Implement the class TokenReader with the methods below; each method is called on fresh inputs and every call's return value is checked.
class TokenReader:
def __init__(self) -> None: ...
def is_well_formed(self, tokens: list[str]) -> bool: ...In is_well_formed, each token is a string.
Part 1: Balanced indentation
A token is the string "INDENT", the string "DEDENT", or a piece of text made of lowercase letters. INDENT opens one nesting level and DEDENT closes the most recently opened one; text tokens do not affect nesting.
Implement is_well_formed(tokens), which takes the list of tokens and returns whether the stream is well formed. The stream is ill formed if either failure happens:
- A
DEDENTarrives while no level is open. The stream is ill formed at that point. - A level is still open at the end of the stream.
Otherwise the stream is well formed. An empty stream is well formed.
- Example 1
- init
[]- operations
[["is_well_formed",[[]]],["is_well_formed",[["hello"]]],["is_well_formed",[["INDENT","a","DEDENT"]]],["is_well_formed",[["INDENT","INDENT","a","DEDENT","b","DEDENT"]]],["is_well_formed",[["INDENT","DEDENT","INDENT","DEDENT"]]],["is_well_formed",[["DEDENT","INDENT"]]],["is_well_formed",[["INDENT"]]]]- Output
[true,true,true,true,true,false,false]
Why: An empty stream and a stream of only text open no levels, so both are well formed.
["INDENT", "a", "DEDENT"]opens and closes one level. In["DEDENT", "INDENT"]the dedent arrives while no level is open, so the stream is not well formed even though the counts ofINDENTandDEDENTare equal.["INDENT"]leaves a level open at the end.
Constraints
0 <= len(tokens) <= 10^5tokens[i]is"INDENT","DEDENT", or1 <= len(tokens[i]) <= 10lowercase letters