字符串的最大重复数

题目:编写递归算法求最大重复数,比如"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 2012-10-25 22:45  小强斋太  阅读(338)  评论(0编辑  收藏  举报

导航