- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在尝试实现一些在多个字符串之间找到公共(public)后缀的东西,为了便于说明,请考虑以下内容:
"The quick brown fox""The not so quick brown fox""The smelly brown fox""The vicious brown fox"
To a human, it's hopefully obvious that the common suffix here is " brown fox"
, and my naive implementation currently takes the first pair of strings, converts them both to char arrays, and then iterates over these until a character is found to be different, I then create a new string from this, and crop it to the length, reverse it back to the correct order, and return that. I then repeat using the result from the first string with the next string in the list.
Whilst this is loosely O(N), performance of this isn't as good as I'd like, and I wondered before I spend a long time buried in the profiler if I'd missed a quicker way to do this within the .NET framework?
EDIT:Taking out the double reverses (which then means we don't need to convert to char arrays) gives pretty good performance, for the record, my implementation looks a little like:
private string GetCommonSuffix(string[] lines)
{
int lineCount = lines.GetLength(0);
string currentSuffix = lines[0];
int currentSuffixLength = currentSuffix.Length;
for (int i = 1; i < lineCount; i++)
{
string thisLine = lines[i];
if (!thisLine.EndsWith(currentSuffix))
{
int thisLineLength = thisLine.Length;
int maxPossible = thisLineLength < currentSuffixLength ? thisLineLength : currentSuffixLength;
if (maxPossible == 0)
{
return string.Empty;
}
for (int j = 1; j < maxPossible; j++)
{
if( currentSuffix[ currentSuffixLength - j ] != thisLine[ thisLineLength - j ] )
{
currentSuffix = currentSuffix.Substring(currentSuffixLength - j + 1, j - 1);
currentSuffixLength = j - 1;
break;
}
}
}
}
return currentSuffix;
}
最佳答案
好吧,首先您不需要将字符串转换为 char 数组。您可以在字符串中使用索引器来获取单个字符。
可能值得将其视为一个数字而不是一个字符串...每次成对比较都会给你一个最大值,而最终的数字(后缀的大小)是最小值这些最大值。
因此有两种方法:
不过,就我个人而言,我可能会选择第一种方法——它不会有很好的缓存一致性,但我认为在某些情况下它会更好(例如,许多字符串,除了其中一个之外,所有的字符串都有一个长的共同点后缀。
(当然,一旦你得到了长度,得到实际的子串就很简单了。)
关于c# - 如何在两个字符串中找到共同的后缀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3906226/
所以,我有一个类似于 this one 的用例,但我觉得有一些额外的细节值得提出一个新问题。 ( related questions ,供引用) 我正在编写一个实现 a cycle 的数据结构.基本设
我正在使用 Django 编写一个社交网络应用程序,需要实现类似于 Facebook“Mutual Friends”概念的功能。我有一个像这样的简单模型: class Friend(models.Mo
我有一个 iOS 应用程序,用户可以在其中使用 Facebook 登录并授予 user_friends 权限。从 Graph API 2.0 开始,Facebook 声称你无法获取两个人之间所有的共同
我想知道将来对我来说最简单的方法是什么,可以使查询既有效又不那么复杂。 我应该像这样保存双向关系吗 from_id=1, to_id=2from_id=2, to_id=1 或者只创建一个唯一的行 f
我是一名优秀的程序员,十分优秀!