传送门:P12035 [USTCPC 2025] Hackergame

更佳的阅读体验:洛谷 P12035 题解


简要题意:给定字符串 $s$,找出 $s$ 中第一个以 $\texttt{flag\{}$ 开头、以 $\texttt{\}}$ 结尾且中间不含 $\texttt{\{}$ 和 $\texttt{\}}$ 的连续子串,存在则输出该子串,否则输出 $\texttt{NOT FOUND}$。

我们可以使用字符串函数 s.find(),从头开始一直寻找以 $\texttt{flag\{}$ 开头的子串。如果发现一个,那么就寻找后面最近的 $\texttt{\}}$。如果可以找到,那么就判断从 $\texttt{flag\{}$ 到 $\texttt{\}}$ 中间有没有 $\texttt{\{}$,有的话说明这个子串是不合法的,继续向后寻找下一个 $\texttt{flag\{}$,直到找到一个合法的为止。

如果已经找到合法的子串,就直接输出,并结束程序。如果找不到,在程序最后输出 $\texttt{NOT FOUND}$ 即可。

#include <iostream>
using namespace std;

string s;

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    cin >> s;
    auto pos = s.find("flag{");
    while (pos != s.npos) {
        auto end = s.find('}', pos);
        if (end == s.npos) break;
        bool fail = false;
        for (int i = pos + 5; i < end && i < s.size(); ++i) if (s[i] == '{') {
            fail = true;
            break;
        } if (!fail) {
            cout << s.substr(pos, end - pos + 1) << '\n';
            return 0;
        } pos = s.find("flag{", pos + 1);
    } cout << "NOT FOUND\n";
    return 0;
}
最后修改:2025 年 04 月 06 日
如果觉得我的文章对你有用,请随意赞赏