结合样例和下面图中的几种情况考虑即可解决。
代码如下:
1 #include <iostream> 2 #include <stack> 3 #include <string> 4 using namespace std; 5 6 int main() { 7 int begin, end; 8 while (cin >> begin >> end, begin != -1 && end != -1) { 9 string text; 10 cin.get(); getline(cin, text); 11 stack<string> prepend, append; 12 for (int cur = 0; cur < begin; ++cur) { 13 if (text[cur] == ‘<‘) { 14 if (text[cur + 1] == ‘/‘) { 15 prepend.pop(); append.pop(); 16 } else { 17 int tail = cur + 1; 18 while (text[tail] != ‘>‘) ++tail; 19 string tag = text.substr(cur, tail - cur + 1); 20 prepend.push(tag); 21 append.push(tag.insert(1, "/")); 22 } 23 } 24 } 25 for (int cur = begin; cur < end; ++cur) { 26 if (text[cur] == ‘<‘) { 27 if (text[cur + 1] == ‘/‘) { 28 append.pop(); 29 } else { 30 int tail = cur + 1; 31 while (text[tail] != ‘>‘) ++tail; 32 string tag = text.substr(cur, tail - cur + 1); 33 append.push(tag.insert(1, "/")); 34 } 35 } 36 } 37 string ans = text.substr(begin, end - begin); 38 while (!prepend.empty()) { 39 ans = prepend.top() + ans; prepend.pop(); 40 } 41 while (!append.empty()) { 42 ans += append.top(); append.pop(); 43 } 44 cout << ans << endl; 45 } 46 return 0; 47 }
时间: 2024-11-05 21:27:21