字符串的最大重复数

题目:编写递归算法求最大重复数,比如"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;
 }	



 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值