看完题目和样例,觉得难以理解;反复看了几遍后,觉得可能出错了,最终在POJ上找到了,就是2813,而在这里已经更正了。
题目说的是一个编写HTML的一个问题,希望我们提取text中的相关内容后,仍然保持着原来的格式规范,换言之就是需要在提取内容中添加必要的tags,以确保提取后的内容和原文的格式保持一致。
方法多种多样了,只是有点麻烦而已,另外注意到出给的样例都是符合HTML编写规范的。我的方法是,先遍历0-B的字符,碰到开始标记的就将其压入prepend栈中,而它对应的结束标记则压入append栈中;若碰到结束标记,由于书写都是合法的,故匹配成功,两个栈都各自pop一下。然后再遍历B-E,若碰到开始标记,将其对应的结束标记压入append栈中;若碰到结束标记,则append栈pop一下。然后将两个栈的内容依次从提取后的字串左右两端分别往外补充即可。
Run Time: 0sec
Run Memory: 312KB
Code Length: 1419Bytes
SubmitTime: 2012-02-24 12:16:56
// Problem#: 1180
// Submission#: 1217648
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <iostream>
#include <string>
#include <stack>
#include <cstdio>
using namespace std;
int main()
{
int B, E;
string text, temp, r;
stack<string> prepend, append;
int i, j;
while ( cin >> B >> E && B != -1 && E != -1 ) {
getchar();
getline( cin, text );
for ( i = 0; i < B; i++ ) if ( text[ i ] == '<' ) {
if ( text[ i + 1 ] == '/' ) {
prepend.pop();
append.pop();
}
else {
j = text.find( '>', i );
temp = text.substr( i, j - i + 1 );
prepend.push( temp );
temp.insert( 1, "/" );
append.push( temp );
i = j;
}
}
for ( i = B; i < E; i++ ) if ( text[ i ] == '<' ) {
if ( text[ i + 1 ] == '/' )
append.pop();
else {
j = text.find( '>', i );
temp = text.substr( i, j - i + 1 );
temp.insert( 1, "/" );
append.push( temp );
i = j;
}
}
r = text.substr( B, E - B );
while ( !prepend.empty() ) {
r = prepend.top() + r;
prepend.pop();
}
while ( !append.empty() ) {
r = r + append.top();
append.pop();
}
cout << r << endl;
}
return 0;
}