看完題目和樣例,覺得難以理解;反覆看了幾遍後,覺得可能出錯了,最終在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;
}