我有两个由空格分隔的包含字母和数字的字符串。例如"elza7ma wa2fa fel matab“和"2ana ba7eb el za7ma 2awy 2awy”
比较这两个字符串以找出它们是否有共同之处的最快方法是什么?
我尝试使用string.split拆分其中一个,并在整个单词数组上使用string.compare。但是这是非常慢的,因为我将会比较很多字符串。
发布于 2010-09-24 07:43:21
一种LINQ解决方案
"elza7ma wa2fa fel matab".Split()
.Intersect("2ana ba7eb el za7ma 2awy 2awy".Split())
.Any();
// as a string extension method
public static class StringExtensions
{
public static bool OneWordMatches(this string theString, string otherString)
{
return theString.Split().Intersect(otherString.Split()).Any();
}
}
// returns true
"elza7ma wa2fa fel matab 2ana".OneWordMatches("2ana ba7eb el za7ma 2awy 2awy");
发布于 2010-09-24 07:44:50
我认为最简单的方法是将字符串拆分成单词,并使用像HashSet<string>
这样的集合结构来检查重复项。例如
public bool HasMatchingWord(string left, string right) {
var hashSet = new HashSet<string>(
left.Split(" ", StringSplitOptions.RemoveEmptyEntries));
return right
.Split(" ", StringSplitOptions.RemoveEmptyEntries)
.Any(x => hashSet.Contains(x));
}
发布于 2010-09-24 07:45:08
您可以按单词拆分这两个字符串,并构建两个哈希表/字典。然后遍历这两个字典,并在第三个字典(Dictionary<string, int>
)中添加递增整数的键。如果第三个字典中的任何关键字的计数超过1,则该单词在两个原始字符串中都存在。
我认为任何解决这个问题的算法都是“慢”的--特别是对于大的输入字符串/许多单词。
https://stackoverflow.com/questions/3785064
复制