在 C++ 中查找字符串中的循环的有效算法和代码?
例如,在“12345123451234512345”中,查找“12345”的有效算法是什么?
用 C++ 编码。
谢谢。
For example, in "12345123451234512345", what is an efficient algorithm to find "12345"?
Coding in C++.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
继续您的单个示例:
12345123451234512345
返回12345
我认为您想要的是找到重复完成大海捞针的最长可能的针,即
1212121212
代码> =>12
,444
=>4
等等。最简单的解决方案是选择第一个字符并遍历字符串比较匹配项。如果在任何时候出现不匹配,请选择前两个字符并比较整个字符串,依此类推,直到窗口大小大于字符串的一半。
复杂度应该是 O(n^2)
您可以根据字符串的长度优化您选择的窗口大小,即窗口大小只能是字符串长度的约数。
Going on your single example:
12345123451234512345
returns12345
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.