写的比较舒服的一道题,小小de了一会bug,体验不错。
#include <bits/stdc++.h>
#define PARA 1
#define HEAD 2
#define UL 3
#define L 4
using namespace std;
string preLine, curLine;
struct block{
vector<string> lines;
};
vector<block> blocks;
vector<string> res;
string pseL(const string& s, int& pos);
string pseE(const string& s, int& pos) { //_xxx_
string ret;
pos++;
ret += "<em>";
for (; pos < s.size(); pos++) {
if (s[pos] == '[') {
ret += pseL(s, pos); // s[pos] = )
} else if (s[pos] == '_') {
break;
} else {
ret.push_back(s[pos]);
}
}
ret += "</em>";
return ret;
}
string pseL(const string& s, int& pos) {
int mod = 0;
string text;
string link;
pos++;
for (; pos < s.size(); pos++) {
if (s[pos] == ']') {
mod = 1;
pos++;
} else if (s[pos] == '_') {
if (mod == 0) {
text += pseE(s, pos);
} else {
link += pseE(s, pos);
}
} else if (s[pos] == ')') {
break;
} else {
if (mod == 0) {
text.push_back(s[pos]);
} else {
link.push_back(s[pos]);
}
}
}
return "<a href=\"" + link + "\">" + text + "</a>";
}
string parseLine(const string& s) {
int pos = 0;
string ret;
for (; pos < s.size(); pos++) {
if (s[pos] == '_') { // 进去是_xxx
ret += pseE(s, pos); // 出来是s[pos] == _
} else if (s[pos] == '[') { // 进去是s[pos] == [
ret += pseL(s, pos); // 出来是s[pos] == )
} else {
ret.push_back(s[pos]);
}
}
return ret;
}
void solveHeader(const string& s) {
int x = s.find(' ');
string preFix = "<h" + to_string(x) +">";
string sufFix = "</h" + to_string(x) + ">";
while (s[x] == ' ') x++;
res.push_back(preFix + parseLine(s.substr(x)) + sufFix);
}
void solveList(const block& blk) {
auto& lines = blk.lines;
string preFix = "<li>";
string sufFix = "</li>";
res.push_back("<ul>");
for (auto& l : lines) {
int lpos = 1;
while (l[lpos] == ' ') lpos++;
int rpos = l.size() - 1;
while (l[rpos] == ' ') rpos--;
int dis = rpos - lpos + 1;
res.push_back(preFix + parseLine(l.substr(lpos, dis)) + sufFix);
}
res.push_back("</ul>");
}
void solveP(const block& blk) {
int cnt = 0;
for (auto& l : blk.lines) {
string ll = parseLine(l);
if (cnt == 0) ll = "<p>" + ll;
if (cnt == blk.lines.size() - 1) ll = ll + "</p>";
res.push_back(ll);
cnt++;
}
}
void solveBlock(const block& blk) {
if (blk.lines.size() == 1 && blk.lines[0][0] == '#') {
solveHeader(blk.lines[0]);
} else if (blk.lines[0][0] == '*') {
solveList(blk);
} else {
solveP(blk);
}
}
void solve() {
for (auto& b : blocks) {
solveBlock(b);
}
for (auto& l : res) {
cout << l << '\n';
}
}
int main() {
block blk;
while (getline(cin, curLine)) {
if (curLine.empty()) {
if (!blk.lines.empty()) {
blocks.push_back(blk);
blk.lines.clear();
}
} else {
blk.lines.push_back(curLine);
}
preLine = curLine;
}
if (!blk.lines.empty()) {
blocks.push_back(blk);
}
solve();
}