- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我想开发一种方法,该方法将返回由作为参数传递的字符串中相同字符组成的最大子字符串的长度,但不使用任何 .NET 库
。
例如,如果我们将 aaacccccdefffgg
作为参数传递,最大的子字符串是 ccccc
并且方法应该返回 5。
这是我的工作解决方案:
public static int GetMaxSubstringLenght(char[] myArray)
{
int max = 0;
for (int i = 0; i < myArray.Length-1; i++)
{
if (myArray.Length == 0)
{
return 0;
}
else
{
int j = i + 1;
int currentMax = 1; // string has some value, so we start with 1
while (myArray[i] == myArray[j])
{
currentMax++;
if (max < currentMax)
{
max = currentMax;
}
j++;
}
}
}
return max;
}
上面的代码将返回预期的结果,但在 for 循环
中会有一些我想避免的不必要的迭代。在第一次迭代中,当 i=0
时,它将比较它直到 j=2
,然后退出 while 循环
并在 开始第二次迭代code>for 循环
将 [1]
索引处的那个与 [2]
进行比较,我们在之前的迭代中已经这样做了。所以基本上,当第一次迭代是完成,下一个应该从j
的最后一个值开始。我怎样才能做到这一点?
提前致谢。
最佳答案
既然你想要“最大的子串......”让我们把 String
作为参数并返回 String
public static String GetMaxSubstring(String value) {
if (String.IsNullOrEmpty(value))
return "";
int bestCount = 0;
char bestChar = '\0';
int currentCount = 0;
char current = '\0';
for (int i = 0; i < value.Length; ++i) {
if ((i == 0) || (value[i] != current))
currentCount = 0;
currentCount += 1;
current = value[i];
if (currentCount > bestCount) {
bestCount = currentCount;
bestChar = current;
}
}
return new String(bestChar, bestCount);
}
....
// "ccccc"
String result = GetMaxSubstring("aaacccccdefffgg");
// 5
int length = result.Length;
关于c# - 相同字符组成的最大子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37703724/
我正在尝试创建一个程序,其中字符串的前三个字符重复给定次数,如下所示: foo('Chocolate', 3) # => 'ChoChoCho' foo('Abc', 3) # => 'AbcAbcA
我有以下字符串: std::string str = "Mode:AAA:val:101:id:A1"; 我想分离一个位于 "val:" 和 ":id" 之间的子字符串,这是我的方法: std::st
DNA 字符串可以是任意长度,包含 5 个字母(A、T、G、C、N)的任意组合。 压缩包含 5 个字母(A、T、G、C、N)的 DNA 字母串的有效方法是什么?不是考虑每个字母表 3 位,我们可以使用
是否有一种使用 levenstein 距离将一个特定字符串与第二个较长字符串中的任何区域进行匹配的好方法? 例子: str1='aaaaa' str2='bbbbbbaabaabbbb' if str
使用 OAuth 并使用以下函数使用我们称为“foo”(实际上是 OAuth token )的字符串加密 key public function encrypt( $text ) { // a
我是一名优秀的程序员,十分优秀!