Sicily 1180. Pasting Strings

本文探讨了如何在处理HTML文本时保持其规范性,通过使用栈数据结构来正确地添加和移除标签,确保提取内容与原始文本一致。方法涉及遍历文本,识别开始和结束标签,并使用栈进行管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看完题目和样例,觉得难以理解;反复看了几遍后,觉得可能出错了,最终在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;

}                                 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值