查找字符串数组的公共前缀
我有一个这样的数组:
$sports = array(
'Softball - Counties',
'Softball - Eastern',
'Softball - North Harbour',
'Softball - South',
'Softball - Western'
);
我想找到字符串的最长公共前缀。在这种情况下,它将是'Softball - '
我想我会遵循这个过程
$i = 1;
// loop to the length of the first string
while ($i < strlen($sports[0]) {
// grab the left most part up to i in length
$match = substr($sports[0], 0, $i);
// loop through all the values in array, and compare if they match
foreach ($sports as $sport) {
if ($match != substr($sport, 0, $i) {
// didn't match, return the part that did match
return substr($sport, 0, $i-1);
}
} // foreach
// increase string length
$i++;
} // while
// if you got to here, then all of them must be identical
对于我的5行数组来说可能没问题,但是如果我要做几千行数组,会有很多开销,所以我必须用 $i
的起始值进行移动计算,例如 $i
= 字符串的一半,如果失败,则 $i/2
直到成功,然后将 $i
加 1 直到成功。这样我们就可以通过最少的比较次数来获得结果。
是否已经有解决此类问题的公式/算法?
I have an array like this:
$sports = array(
'Softball - Counties',
'Softball - Eastern',
'Softball - North Harbour',
'Softball - South',
'Softball - Western'
);
I would like to find the longest common prefix of the string. In this instance, it would be 'Softball - '
I am thinking that I would follow this process
$i = 1;
// loop to the length of the first string
while ($i < strlen($sports[0]) {
// grab the left most part up to i in length
$match = substr($sports[0], 0, $i);
// loop through all the values in array, and compare if they match
foreach ($sports as $sport) {
if ($match != substr($sport, 0, $i) {
// didn't match, return the part that did match
return substr($sport, 0, $i-1);
}
} // foreach
// increase string length
$i++;
} // while
// if you got to here, then all of them must be identical
For my 5 lines array that is probably fine, but if I were to do several thousand lines arrays, there would be a lot of overhead, so I would have to be move calculated with my starting values of $i
, eg $i
= halfway of string, if it fails, then $i/2
until it works, then increment $i
by 1 until we succeed. So that we are doing the least number of comparisons to get a result.
Is there a formula/algorithm out already out there for this kind of problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(16)
如果您可以对数组进行排序,那么就有一个简单且非常快速的解决方案。
只需将第一项与最后一项进行比较即可。
如果字符串已排序,则所有字符串共有的任何前缀对于已排序的第一个和最后一个字符串也将是通用的。
If you can sort your array, then there is a simple and very fast solution.
Simply compare the first item to the last one.
If the strings are sorted, any prefix common to all strings will be common to the sorted first and last strings.
我会使用这个:
更新
这是另一个解决方案,迭代地比较字符串的每个第 n 个字符,直到发现不匹配:
这甚至更有效,因为最多只有 numberOfStrings·commonPrefixLength原子比较。
I would use this:
Update
Here’s another solution, iteratively comparing each n-th character of the strings until a mismatch is found:
This is even more efficient as there are only at most numberOfStrings·commonPrefixLength atomic comparisons.
我在代码中实现了@diogoriba算法,结果如下:
我实现的另一个想法:
首先检查数组中最短的字符串,然后使用它进行比较,而不是简单地使用第一个字符串。 在代码中,这是通过自定义编写的函数 arrayStrLenMin() 实现的。
以尽可能少的迭代次数获取数组中字符串的最大公共前缀(PHP)
代码+广泛测试+备注:
I implemented @diogoriba algorithm into code, with this result:
Another idea I implemented:
First check for the shortest string in the array, and use this for comparison rather than simply the first string. In the code, this is implemented with the custom written function arrayStrLenMin().
Get the maximum common prefix of strings in an array with as little iterations as possible (PHP)
Code + Extensive Testing + Remarks:
可能有一些非常受好评的算法,但就在我的脑海中,如果你知道你的共性将在左侧,就像你的例子一样,你可以做得比你发布的方法更好首先找到前两个字符串的共性,然后向下迭代列表的其余部分,根据需要修剪公共字符串以实现共性,或者如果一直修剪到无,则以失败终止。
Probably there is some terribly well-regarded algorithm for this, but just off the top of my head, if you know your commonality is going to be on the left-hand side like in your example, you could do way better than your posted methodology by first finding the commonality of the first two strings, and then iterating down the rest of the list, trimming the common string as necessary to achieve commonality or terminating with failure if you trim all the way to nothing.
我认为你走在正确的道路上。 而不是在所有字符串都通过时递增 i。
但是,您可以这样做: 1) 比较数组中的前 2 个字符串并找出它们有多少个公共字符, 例如,将常见字符保存在名为 maxCommon 的单独字符串中。
2) 将第三个字符串与 maxCommon 进行比较。如果公共字符的数量较少,则将 maxCommon 修剪为匹配的字符。
3) 重复并冲洗阵列的其余部分。在该过程结束时,maxCommon 将具有所有数组元素所共有的字符串。
这会增加一些开销,因为您需要将每个字符串与 maxCommon 进行比较,但会大大减少获得结果所需的迭代次数。
I think you're on the right way. But instead of incrementing i when all of the string passes, you could do this:
1) Compare the first 2 strings in the array and find out how many common characters they have. Save the common characters in a separate string called maxCommon, for example.
2) Compare the third string w/ maxCommon. If the number of common characters is smaller, trim maxCommon to the characters that match.
3) Repeat and rinse for the rest of the array. At the end of the process, maxCommon will have the string that is common to all of the array elements.
This will add some overhead because you'll need to compare each string w/ maxCommon, but will drastically reduce the number of iterations you'll need to get your results.
我认为“公共部分”的意思是“最长的公共前缀”。这比任何常见的子串都更容易计算。
在最坏的情况下,如果不读取
(n+1) * m
个字符,在最好的情况下读取n * m + 1
字符,则无法完成此操作,其中n
code> 是最长公共前缀的长度,m
是字符串的数量。一次比较一个字母即可实现这种效率(Big Theta (n * m))。
您提出的算法在 Big Theta(n^2 * m) 中运行,对于大输入来说,这要慢得多。
第三种提出的算法是找到前两个字符串的最长前缀,然后与第三个、第四个等进行比较,其运行时间也在 Big Theta(n * m) 中,但具有更高的常数因子。在实践中它可能只会稍微慢一些。
总的来说,我建议只滚动你自己的函数,因为第一个算法太慢,而另外两个算法编写起来也同样复杂。
查看 WikiPedia 了解 Big Theta 表示法的说明。
I assume that by "common part" you mean "longest common prefix". That is a much simpler to compute than any common substring.
This cannot be done without reading
(n+1) * m
characters in the worst case andn * m + 1
in the best case, wheren
is the length of the longest common prefix andm
is the number of strings.Comparing one letter at a time achieves that efficiency (Big Theta (n * m)).
Your proposed algorithm runs in Big Theta(n^2 * m), which is much, much slower for large inputs.
The third proposed algorithm of finding the longest prefix of the first two strings, then comparing that with the third, fourth, etc. also has a running time in Big Theta(n * m), but with a higher constant factor. It will probably only be slightly slower in practice.
Overall, I would recommend just rolling your own function, since the first algorithm is too slow and the two others will be about equally complicated to write anyway.
Check out WikiPedia for a description of Big Theta notation.
不知道
是的:您可以简单地检查第 i 个字符(您已经知道字符 0 到 i-),而不是比较从 0 到长度 i 的子字符串1 匹配)。
not that I know of
yes: instead of comparing the substring from 0 to length i, you can simply check the ith character (you already know that characters 0 to i-1 match).
这是 JavaScript 中的一个优雅的递归实现:
Here's an elegant, recursive implementation in JavaScript:
简短而甜蜜的版本,也许不是最有效的:
测试用例的输出:
Short and sweet version, perhaps not the most efficient:
Output of the test case:
@bumperbox
您的基本代码需要进行一些修正才能在所有场景中工作!
目前您的算法失败
在我的下一个答案/帖子中,我将附上迭代优化的代码!
原始 Bumperbox 代码加上更正 (PHP):
@bumperbox
Your basic code needed some correction to work in ALL scenarios!
Currently your algorithm fails
In my next answer/post, I will attach iteration optimized code!
Original Bumperbox code PLUS correction (PHP):
我会使用这样的递归算法:
1 - 获取数组中的第一个字符串
2 - 使用第一个字符串作为参数调用递归前缀方法
3 - 如果前缀为空则返回无前缀
4 - 循环遍历数组中的所有字符串
4.1 - 如果任何字符串不以前缀开头
4.1.1 - 使用前缀 - 1 作为参数调用递归前缀方法
4.2 返回前缀
I would use a recursive algorithm like this:
1 - get the first string in the array
2 - call the recursive prefix method with the first string as a param
3 - if prefix is empty return no prefix
4 - loop through all the strings in the array
4.1 - if any of the strings does not start with the prefix
4.1.1 - call recursive prefix method with prefix - 1 as a param
4.2 return prefix
最上面的答案似乎有点长,所以这里有一个运行时间为 O(n2) 的简洁解决方案。
The top answer seemed a bit long, so here's a concise solution with a runtime of O(n2).
无论如何,这是我想出的另一种选择。
我用它来查找产品代码列表的公共前缀(即,有多个产品 SKU 开头有一系列公共字符):
For what it's worth, here's another alternative I came up with.
I used this for finding the common prefix for a list of products codes (ie. where there are multiple product SKUs that have a common series of characters at the start):
这是对@Gumbo 答案的补充。如果您想确保所选的公共前缀不会断词,请使用此前缀。我只是让它在所选字符串末尾查找空格。如果存在,我们知道所有短语都有更多内容,因此我们将其截断。
This is an addition to the @Gumbo answer. If you want to ensure that the chosen, common prefix does not break words, use this. I am just having it look for a blank space at the end of the chosen string. If that exists we know that there was more to all of the phrases, so we truncate it.
(“如果我要做几千行数组”)
这个数据结构是 Trie(前缀树):一种树状数据结构,用于存储动态字符串集,其中每个节点代表单个字符。
时间效率:搜索、插入和插入删除:时间复杂度为O(m),其中m是字符串的长度。
空间效率:存储字符串中存在的唯一字符。与存储整个字符串相比,这可能具有空间优势。
--
输入的 Trie 可视化(绿色节点标记为:endOfString):
--
PHP 实现:
输出:
演示
("if I were to do several thousand lines arrays")
The data structure for this is a Trie (Prefix Tree): A tree-like data structure used to store a dynamic set of strings where each node represents a single character.
Time Efficiency: Search, Insertion & Deletion: With a time-complexity of O(m) where m is the length of the string.
Space Efficiency: Store the unique characters present in the strings. This can be a space advantage compared to storing the entire strings.
--
Trie Visualization for your input (Green nodes are marked: endOfString):
--
PHP implementation:
Output:
Demo