Create a table of contents for a simple markup language. It must follow two rules:
- If a line starts with a single
#followed by a space, then it is a chapter title. - If a line starts with a double
##followed by a space, then it is a section title.
The table of contents should be displayed in the following format:
1. Title of the first chapter
1.1. Title of the first section of the first chapter
1.2. Title of the second section of the first chapter
...
2. Title of the second chapter
2.1. Title of the first section of the second chapter
2.2. Title of the second section of the second chapter
...
Note that each number is followed by a period and the last period is followed by 1 space.
For example, the input text is n = 10 lines long, where text is:
10
# Cars
Cars came into global use during the 20th century
Most definitions of car say they run primarily on roads
## Sedan
Sedan's first recorded use as a name for a car body was in 1912
## Coupe
A coupe is a passenger car with a sloping rear roofline and generally two doors
## SUV
The predecessors to SUVs date back to military and low-volume models from the late 1930s
There is no commonly agreed definition of an SUV, and usage varies between countries.
Sample Output
1. Cars
1.1. Sedan
1.2. Coupe
1.3. SUV
Explanation: The first line of input indicates there are n = 10 lines of text. There is only 1 chapter in the input, and it contains 3 sections. All lines that do not begin with # or ## are ignored in the table of contents.
这道题要求根据输入文本中的标题标记生成目录:以“#”开头的行表示章节标题,以“##”开头的行表示小节标题,其他行全部忽略。关键在于按顺序维护章节编号和小节编号,当出现新章节时小节编号重置;输出格式必须严格符合“1. 标题”“1.1. 标题”这种层级编号形式。实现时通常只需线性扫描每一行文本,结合字符串前缀判断即可完成,适合用计数器模拟目录层级。