我有一个字符串列表和每个字符串我想检查它的字符对每个其他字符串,看看它的所有字符是否相同,除了一个。
例如,将返回true的检查将是检查
摇滚锁
时钟和羊群有一个不同的角色,不多也不少。
对抗凹痕的岩石显然会返回虚假。
我一直在考虑首先循环遍历列表,然后在该列表中有一个辅助循环来检查第一个字符串与第二个字符串。
然后使用split(""); 创建两个包含每个字符串的字符的数组,然后相互检查数组元素(即比较每个字符串与另一个数组中的相同位置1-1 2-2等),并且只要一个字符比较失败然后检查这两个字符串是否为真。
无论如何,我有很多字符串(4029)并且考虑到我现在想要实现的内容将包含3个循环,每个循环都会产生一个立方循环(?),这将花费很长时间来处理那么多元素不是吗?
有更简单的方法吗? 或者这种方法真的可行吗? 或者 - 但是 - 但是在我提出的解决方案中是否存在某种潜在的逻辑缺陷?
非常感谢!
I have a list of strings and with each string I want to check it's characters against every other string to see if all it's characters are identical except for one.
For instance a check that would return true would be checking
rock against lock
clock and flock have one character that is different, no more no less.
rock against dent will obviously return false.
I have been thinking about first looping through the list and then having a secondary loop within that one to check the first string against the second.
And then using split(""); to create two arrays containing the characters of each string and then checking the array elements against each other (i.e. comparing each string with the same position in the other array 1-1 2-2 etc...) and so long as only one character comparison fails then the check for those two strings is true.
Anyway I have a lot of strings (4029) and considering what I am thinking of implementing at the moment would contain 3 loops each within the other that would result in a cubic loop(?) which would take a long long time with that many elements wouldn't it?
Is there an easier way to do this? Or will this method actually work okay? Or -hopefully not- but is there some sort of potential logical flaw in the solution I have proposed?
Thanks a lot!
最满意答案
为什么不以天真的方式做呢?
bool matchesAlmost(String str1, String str2) { if (str1.length != str2.length) return false; int same = 0; for (int i = 0; i < str1.length; ++i) { if (str1.charAt(i) == str2.charAt(i)) same++; } return same == str1.length - 1; }现在你可以使用二次算法来检查每个字符串。
Why not do it the naive way?
bool matchesAlmost(String str1, String str2) { if (str1.length != str2.length) return false; int same = 0; for (int i = 0; i < str1.length; ++i) { if (str1.charAt(i) == str2.charAt(i)) same++; } return same == str1.length - 1; }Now you can just use a quadratic algorithm to check every string against every other.
更多推荐
发布评论