gpt4 book ai didi

java - 在字符串中查找最长字符条纹的有效方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:59:41 26 4
gpt4 key购买 nike

此代码运行良好,但我正在寻找优化它的方法。如果您查看长字符串,您会看到“l”连续出现了五次。没有其他角色连续出现这么多次。所以,输出是 5。现在,问题是这个方法检查每个字符,甚至在找到最大值后,它继续检查剩余的字符。有没有更有效的方法?

public class Main {
public static void main(String[] args) {
System.out.println(longestStreak("KDDiiigllllldddfnnlleeezzeddd"));
}
private static int longestStreak(String str) {
int max = 0;
for (int i = 0; i < str.length(); i++) {
int count = 0;
for (int j = i; j < str.length(); j++) {
if (str.charAt(i) == str.charAt(j)) {
count++;
} else break;
}
if (count > max) max = count;
}
return max;
}
}

最佳答案

我们可以在单次迭代中为先前的字符计数添加变量。同样作为额外的优化,我们在 i + max - currentLenght < str.length() 时停止迭代。 .这意味着不能更改 max:

private static int longestStreak(String str) {
int maxLenght = 0;
int currentLenght = 1;
char prev = str.charAt(0);
for (int index = 1; index < str.length() && isMaxCanBeChanged(str, maxLenght, currentLenght, index); index++) {
char currentChar = str.charAt(index);
if (currentChar == prev) {
currentLenght++;
} else {
maxLenght = Math.max(maxLenght, currentLenght);
currentLenght = 1;
}
prev = currentChar;
}
return Math.max(maxLenght, currentLenght);
}

private static boolean isMaxCanBeChanged(String str, int max, int currentLenght, int index) {
return index + max - currentLenght < str.length();
}

关于java - 在字符串中查找最长字符条纹的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58120050/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com