字符串的最大重复数

题目:编写递归算法求最大重复数,比如"aaabbcc"的最大重复数为3,"aab"最大重复数为2

import junit.framework.TestCase;

public class RepeatTimes1 extends TestCase {

	// 判断一个字符在某个字符串中出现的次数
	public int existsTimes(String str, char c) {
		int count = 0;
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) == c)
				count++;
		}
		return count;
	}

	// 递归 求字符串中最大的重复数
	public int repeatTimes(String str) {
		if (str== null||"".equals(str)) return 0;
		if (str.length() == 1)
			return 1; // 字符串长度为1时,最大重复数肯定为1
		else {
			int time1 = repeatTimes(str.substring(1));// 子串的重复数
			int time2 = existsTimes(str.substring(1), str.charAt(0));// 字符串首字母在子串出现的次数

			if (time2 < time1) // 字符串首字母在子串出现的次数小于子串的重复数
				return time1;
			else
				return time2 + 1; // 字符串首字母在子串出现的次数大于子串的重复数

		}
	}
	
	public void test() {
		System.out.println(repeatTimes("1232"));
	}

}

非递归方法

//非递归方法
 public int repeatTimes(String str) {
  if (str== null||"".equals(str)) return 0;
  if (str.length() == 1)
   return 1; // 字符串长度为1时,最大重复数肯定为1
  int c[] =new int[256];
  for (int i = 0; i < str.length(); i++) {
   c[str.charAt(i)]++;
  }
  
  int max=c[0];
  for (int i = 0; i < c.length; i++) {
   if(c[i]>c[0]) max=c[i];
  }
  return max;
 }	



 

 

posted on   小强斋太  阅读(347)  评论(0编辑  收藏  举报

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律

导航

< 2012年10月 >
30 1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31 1 2 3
4 5 6 7 8 9 10
点击右上角即可分享
微信分享提示