zoukankan      html  css  js  c++  java
  • 字符串的最大重复数 小强斋

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



     

  • 相关阅读:
    Linux文件与目录管理(一)
    Linux文件基本属性
    软工实践总结
    微软必应词典的调查与研究
    调研安卓开发环境的发展演变
    软件工程的预定目标
    学习进度第5周
    机械学习----KNN算法
    MyBatis:简介、第一个程序01(纯小白非常实用)
    解决数据库连接时区的问题
  • 原文地址:https://www.cnblogs.com/xiaoqiangzhaitai/p/5429429.html
Copyright © 2011-2022 走看看