1. Table of Contents
Create a table of contents for a simple markup language. It must follow two rules:
1. If a line starts with a single # followed by a space, then it's a chapter title.
2. If a line starts with a double # followed by a space, then it's 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 = 12 lines long, where text is the following:
#Algorithms
This chapter covers the most basic algorithms.
## Sorting
Quicksort is fast and widely used in practice
Merge sort is a deterministic algorithm
## Searching
DFS and BFS are widely used graph searching algorithms
Some variants of DFS are also used in game theory applications
Data Structures
This chapter is all about data structures
It's a draft for now and will contain more sections in the future
#Binary Search Trees
This is the table of contents that must be produced:
1. Algorithms
1.1. Sorting
1.2. Searching
2. Data Structures
3. Binary Search Trees
c++
vector<string> tableOfContents(vector<string> text) {
vector<string> toc;
int chapterCount = 0;
int sectionCount = 0;
for (const string& line : text) {
if (line.size() >= 3 && line.substr(0, 2) == "##") { // Section title
sectionCount++;
stringstream ss(line.substr(3));
string sectionTitle;
getline(ss, sectionTitle);
toc.push_back(to_string(chapterCount) + "." + to_string(sectionCount) + ". " + sectionTitle);
} else if (line.size() >= 2 && line[0] == '#') { // Chapter title
chapterCount++;
sectionCount = 0;
stringstream ss(line.substr(2));
string chapterTitle;
getline(ss, chapterTitle);
toc.push_back(to_string(chapterCount) + ". " + chapterTitle);
}
}
return toc;
}