201509-3 模板生成系统

这篇博客展示了两种不同的代码实现,用于处理字符串模板替换。90分代码使用C++标准库的`find`和`substr`函数,但可能在处理大量数据时导致超时。100分代码采用`unordered_map`存储变量并遍历字符串进行替换,提高了效率。讨论了如何在字符串处理中避免超时并提高程序性能。
摘要由CSDN通过智能技术生成

90分代码,用string自带的函数会超时。

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=1e2+5,INF=0x3f;
string s[maxn];
int main()
{
    int n,m;
    cin>>m>>n;
    getchar();
    for(int i=0;i<m;i++)
        {
            getline(cin,s[i]);
            //cout<<s[i]<<endl;
        }
    for(int i=0;i<n;i++)
    {
        string s1,s2,s3;
        cin>>s1;
        getline(cin,s2);
        s3=s2.substr(2,s2.size()-3);
        //cout<<s3<<endl;
        //cout<<s1<<" "<<s2<<endl;
        for(int j=0;j<m;j++)
            {
                while(1)
                {
                    int cur=s[j].find("{{ "+s1+" }}");
                    if(cur!=s[j].npos)
                        {
                            s[j].erase(cur,6+s1.size());
                            s[j].insert(cur,s3);
                        }
                    else break;
                }
                //cout<<s[j]<<endl;
            }
    }
    for(int j=0;j<m;j++)
        {
            while(1)
            {
                int cur1=s[j].find("{{ "),cur2=s[j].find(" }}");
                if(cur1!=s[j].npos&&cur2!=s[j].npos)
                {
                    s[j].erase(s[j].begin()+cur1,s[j].begin()+cur2+3);
                }
                else break;
            }
        }
    for(int j=0;j<m;j++)
        cout<<s[j]<<endl;
    return 0;
}

100分y总代码

#include <iostream>
#include <cstring>
#include <algorithm>
#include <unordered_map>
#include <vector>

using namespace std;

int n, m;
vector<string> strs;
unordered_map<string, string> vars;

int main()
{
    cin >> n >> m;
    getchar();  // 过滤掉第一行的回车
    while (n -- )
    {
        string str;
        getline(cin, str);
        strs.push_back(str);
    }
    while (m -- )
    {
        string key, value;
        cin >> key;
        char c;
        while (c = getchar(), c != '\"');
        while (c = getchar(), c != '\"') value += c;
        vars[key] = value;
    }

    for (auto& str: strs)
    {
        for (int i = 0; i < str.size();)
            if (i + 1 < str.size() && str[i] == '{' && str[i + 1] == '{')
            {
                int j = i + 3;
                string key;
                while (str[j] != ' ' || str[j + 1] != '}' || str[j + 2] != '}')
                    key += str[j ++ ];
                cout << vars[key];
                i = j + 3;
            }
            else cout << str[ i ++ ];
        cout << endl;
    }
    return 0;
}

作者:yxc
链接:https://www.acwing.com/activity/content/code/content/872378/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值