简述:
用递归找一个字符串中 最长连续出现的字符的个数
例如:
“abbbbbbc"返回的就是6
package offer;
public class GetLongestConsecutiveSubString {
//递归实现找出字符串中连续出现次数最大的字符的长度
private int getLongestConsecutiveSubString(String str, int currentPos, int count, int maxLength){
if(currentPos == str.length()){
return maxLength;
}
if(str.charAt(currentPos) == str.charAt(currentPos - 1)){
count++;
if(count > maxLength)
maxLength = count;
}else{
count = 1;
}
return getLongestConsecutiveSubString(str, currentPos + 1, count, maxLength);
}
public int GetResult(String str){
if(str == null || str.isEmpty())
return 0;
if(str.length() == 1)
return 1;
return getLongestConsecutiveSubString(str, 1, 1, 1);
}
public static void main(String[] args) {
GetLongestConsecutiveSubString obj = new GetLongestConsecutiveSubString();
System.out.println(obj.GetResult("abbbbbbc"));
}
}
本文介绍了一种使用递归方法寻找字符串中连续出现次数最多的字符及其长度的算法实现。通过具体示例代码,展示了如何针对不同输入情况(如空字符串、单一字符等)进行有效处理,并给出了一段用于验证正确性的示例程序。
1036

被折叠的 条评论
为什么被折叠?



