我有一个 std::string
类型的变量。我想检查它是否包含某个 std::string
。我该怎么做?
如果找到字符串,是否有一个函数返回true,如果没有,则返回false?
原文由 neuromancer 发布,翻译遵循 CC BY-SA 4.0 许可协议
我有一个 std::string
类型的变量。我想检查它是否包含某个 std::string
。我该怎么做?
如果找到字符串,是否有一个函数返回true,如果没有,则返回false?
原文由 neuromancer 发布,翻译遵循 CC BY-SA 4.0 许可协议
注意:我知道这个问题需要一个函数,这意味着用户正在尝试找到更简单的东西。但我仍然发布它以防有人发现它有用。
使用后缀自动机的方法。它接受一个字符串(haystack),然后您可以输入数十万个查询(needles)并且响应将非常快,即使 haystack 和/或 needle 是非常长的字符串。
阅读此处使用的数据结构: https ://en.wikipedia.org/wiki/Suffix_automaton
#include <bits/stdc++.h>
using namespace std;
struct State {
int len, link;
map<char, int> next;
};
struct SuffixAutomaton {
vector<State> st;
int sz = 1, last = 0;
SuffixAutomaton(string& s) {
st.assign(s.size() * 2, State());
st[0].len = 0;
st[0].link = -1;
for (char c : s) extend(c);
}
void extend(char c) {
int cur = sz++, p = last;
st[cur].len = st[last].len + 1;
while (p != -1 && !st[p].next.count(c)) st[p].next[c] = cur, p = st[p].link;
if (p == -1)
st[cur].link = 0;
else {
int q = st[p].next[c];
if (st[p].len + 1 == st[q].len)
st[cur].link = q;
else {
int clone = sz++;
st[clone].len = st[p].len + 1;
st[clone].next = st[q].next;
st[clone].link = st[q].link;
while (p != -1 && st[p].next[c] == q) st[p].next[c] = clone, p = st[p].link;
st[q].link = st[cur].link = clone;
}
}
last = cur;
}
};
bool is_substring(SuffixAutomaton& sa, string& query) {
int curr = 0;
for (char c : query)
if (sa.st[curr].next.count(c))
curr = sa.st[curr].next[c];
else
return false;
return true;
}
// How to use:
// Execute the code
// Type the first string so the program reads it. This will be the string
// to search substrings on.
// After that, type a substring. When pressing enter you'll get the message showing the
// result. Continue typing substrings.
int main() {
string S;
cin >> S;
SuffixAutomaton sa(S);
string query;
while (cin >> query) {
cout << "is substring? -> " << is_substring(sa, query) << endl;
}
}
原文由 Chris Vilches 发布,翻译遵循 CC BY-SA 4.0 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答2.7k 阅读✓ 已解决
使用
std::string::find
如下:注:“找到了!” will be printed if
s2
is a substring ofs1
, boths1
ands2
are of typestd::string
.