在 C++ 中查找字符串中的循环的有效算法和代码?

发布于 2024-10-06 07:45:06 字数 83 浏览 0 评论 0原文

例如,在“12345123451234512345”中,查找“12345”的有效算法是什么?

用 C++ 编码。

谢谢。

For example, in "12345123451234512345", what is an efficient algorithm to find "12345"?

Coding in C++.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泪之魂 2024-10-13 07:45:06

继续您的单个示例:

12345123451234512345 返回 12345

我认为您想要的是找到重复完成大海捞针的最长可能的针,即 1212121212代码> => 12, 444 => 4等等。

最简单的解决方案是选择第一个字符并遍历字符串比较匹配项。如果在任何时候出现不匹配,请选择前两个字符并比较整个字符串,依此类推,直到窗口大小大于字符串的一半。

复杂度应该是 O(n^2)

您可以根据字符串的长度优化您选择的窗口大小,即窗口大小只能是字符串长度的约数。

Going on your single example:

12345123451234512345 returns 12345

I think what you want is to find the longest possible needle that is repeated to complete the haystack, i.e. 1212121212 => 12, 444 => 4 and so on.

The simplest solution would be to pick the first character and run through the string comparing for matches. If at any point you have a mismatch, pick the first two characters and run through the entire string comparing and so on, until your window size becomes greater than half the string.

Complexity should be O(n^2)

You can optimize which window size you pick based on the length of the string, i.e. the window sizes can only be divisors of the length of the string.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文