2023-09-01
算法题解
00
请注意,本文编写于 76 天前,最后修改于 76 天前,其中某些信息可能已经过时。

目录

题目理解
方法介绍
上代码
换一条赛道(逃)

虽然题目水,但咱不能水啊
借此学一学 Cpp STL 罢~

在本文中,可以看到:

  1. 介绍如何使用 std::basic_string<...>::replace
  2. 如何用 Python 一力破万法

传送门:Luogu P7674 EKSPLOZIJA

题目理解

这个题目的意思很好理解,简单来说坑点如下(可能不算坑点?)

  • 消除后 可能会出现更多能消除的串

所以不能简单的特判

方法介绍

众所周知,string 类 (严格来讲是 basic_string) 中提供了一个方法叫 replace(下方仅简述, 详见 Cppreference), 在这里用到的原型如下

cpp
basic_string& replace(size_type pos, size_type count, const basic_string& str); // pos: 替换的起始位置 // count: 需要替换的字符数量 // str: 替换后的字符串

如果没有用过这个函数, 可能这样不算好理解, 下面给一个简单的例子

cpp
#include <iostream> #include <cstdio> #include <string> using std::string; using std::cin; using std::cout; string str, t; int main() { cin>>str; // stdin: CornWorld\n str="CornWorld" cout<<str.replace(0, 4, "")<<'\n'; // stdout: World\n str="World" printf("%s\n", str.replace(0, 0, "Corn").c_str()); // stdout: CornWorld\n str=CornWorld t="Corn"; cout<<str.replace(str.find(t), t.length(), "AWA")<<'\n'; // stdout: AWAWorld str=AWAWorld\n return 0; }

在这个例子中, 我们可以发现 replace 这个函数会影响原串, 这在用的时候需要注意 QWQ

上代码

那么根据上面的用法, 不难写出来如下代码

cpp
#include <cstdio> #include <string> #include <iostream> using std::string; using std::cin; string ori_str, r_str; string::size_type pos, r_str_len; int main() { cin>>ori_str>>r_str; r_str_len=r_str.length(); while((pos=ori_str.find(r_str))!=string::npos) { ori_str.replace(pos,r_str_len,""); } if(ori_str.empty()) printf("FRULA\n"); else printf("%s\n",ori_str.c_str()); return 0; }

这时候你就可以快乐的拿到 96 pts

换一条赛道(逃)

这时候就有人说:你这不 A 不掉吗? 我直接:Python 大法好!

众所周知,Python 自带正则库 (re — Regular expression operations — Python 3.10.0 documentation),而且实测效率不错。

循环正则替换,那么这个题就能 6 行秒了

python
import re s = input().strip() b = input().strip() while b in s: s = re.sub(b, '', s) if len(s) : print(s) else : print("FRULA")

本文作者:CornWorld

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!