ccf-csp 202006-3 markdown渲染器(c/c++)

ccf-csp 202006-3 markdown渲染器(c/c++)

题目就不过多描述了,就是针对markdown的两种格式段落列表进行行数的计数。这个问题可能处理起来比较麻烦,接下来简要介绍一下我的做法吧。

我定义了几个状态,下面就是几个状态的转化关系,在状态转化的过程中就进行计数。

dErxnU.png

下面是代码部分:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <string>
#include <map>
#include <iostream>
using namespace std;
void eraseSpace(string &s) { // 去除空格
s.erase(0, s.find_first_not_of(" "));
s.erase(s.find_last_not_of(" ")+1, s.size());
}
int lineCount(string s, int width){ // 计算行数
for(int i = width; i < s.size(); i+=width){
while(s[i] == ' '){
s.replace(i, 1, "");
}
}
return int(s.size() - 1)/width + 1;
}
int main() {
ios::sync_with_stdio(false);
string temp, str; // 分别用于存放每次输入的字符串和最终的字符串
int width, status = 0, count = -1, lastStatus = 0; // 显示宽度,当前状态,记录行数,上一个状态
cin>>width;
while(!cin.eof()){
getline(cin, temp);
lastStatus = status; // 记录上一个状态
if(temp.size() >= 2 && temp[0] == '*' && temp[1] == ' '){ // 状态1:列表第一行
status = 1;
}
else if(temp.find_last_not_of(" ") == -1){ // 状态0:空行
status = 0;
}
else if((status == 1 || status == 2) && temp.size() >= 2 && temp[0] == ' ' && temp[1] == ' '){ // 状态2:列表后续行
status = 2;
}
else{ // 状态4:段落
status = 3;
}
if((status != 0 && lastStatus == 0) || ((lastStatus == 1||lastStatus == 2) && status == 3) || (lastStatus == 3 && status == 1)){
count ++; // 出现空行时,或者状态在段落和列表之前切换时,要加一行
}
if(lastStatus == 3 && status != lastStatus){
count += lineCount(str, width); // 完成整个段落时进行计数
}
else if((lastStatus == 1 || lastStatus == 2) && status != 2){
count += lineCount(str, width-3); // 完成整个列表时计数时进行计数
}
switch(status){ // 以下是不同状态时对字符串的处理
case 0:{
break;
}
case 1:{
str = "";
temp.erase(0,2);
eraseSpace(temp);
str = temp;
break;
}
case 2:{
temp.erase(0,2);
eraseSpace(temp);
if(str.size() != 0){
temp = " " + temp;
}
str = str + temp;
break;
}
case 3:{
if (lastStatus != 3){
str = "";
}
eraseSpace(temp);
if(str.size() != 0){
temp = " " + temp;
}
str += temp;
break;
}
default:{
break;
}
}
}
// 完成整个输入过程后,对最后一次的字符进行计数
if(status == 1 || status == 2){
count += lineCount(str, width-3);
}
else if(status == 3){
count += lineCount(str, width);
}
cout<<count<<endl;
return 0;
}

上传结果:

dEsmHe.png