黑马程序员技术交流社区
标题:
字符串求最多出现的次数的问题
[打印本页]
作者:
Tesla时光
时间:
2012-9-11 12:29
标题:
字符串求最多出现的次数的问题
本帖最后由 翁发达 于 2012-9-11 21:30 编辑
/*随机输入一个字符串,找出字符串中出现次数最多的字符是什么,出现了几次
(若出现重复,则按字典顺序哪个先出现,为哪个)
思路:
首先将字符串转换成一个char型数组.
再将char里每一个元素与字符串里的所有元素比较.得到出现的次数
每个出现的次数用一个int型数组接收.
然后查找出这个int型数组的最大值.
这个最大值当下标所对应的char数组的元素就是出现次数最多的字符,出现的次数就是最大值.
*/
现在思路到这里,有一个bug无法想到解决办法,那就是出现重复的情况的处理方式?
要求是要按字典顺序为准,我下面的代码要作什么修改才能实现?
哪位朋友帮解决下,谢谢
import java.util.*;
class Test4
{
public static void main(String[] args)
{
Scanner sc =new Scanner(System.in);
String s =sc.nextLine();
char [] arr = s.toCharArray();
int [] arr1 =new int[arr.length];
for (int x=0;x<arr.length ;x++ )
{
arr1[x]=get(s,arr[x]);
}
int b =set(arr1);
char ch =charAt(b);
System.out.println(ch);
System.out.println("出现最多的字符是"+arr
+",出现了"+arr1
+"次");
}
//求每个元素出现有次数.
public static int get(String s, char c)
{
int count = 0;
int b =0;
while(b!=-1)
{
b = s.indexOf(c,b);
if (b!=-1)
{
b+=1;
count++;
}
}
return count;
}
//求最大值的下标.
public static int set(int[] arr)
{
int a =0;
for (int x =0;x<arr.length ; x++)
{
if (arr[a]<arr[x])
{
a=x;
}
}
return a;
}
}
作者:
AngieFans85
时间:
2012-9-11 14:05
/**
* 找出指定字符串中,每个字符出现次数最多的那个字符,并打印出来.
*
* @param str
* 指定的字符串
* @return 将每个字符出现的次数都保存进TreeMap中,由用户自主选择是不是需要使用这个返回值.
*/
public static TreeMap<String, Integer> getManyCount(String str) {
// 定义正则需要的两个对象
Pattern pattern = null;
Matcher matcher = null;
// 需要定义一个TreeMap才容易使用需求
TreeMap<String, Integer> treeMap = new TreeMap<String, Integer>();
// 用来接收指定字符串中每个字符的值
String s = null;
// 迭代器就不多解释了
Iterator<Entry<String, Integer>> iterator = null;
Entry<String, Integer> next = null;
// 用来接收出现次数最多的那个值
int max = 0;
// 用来接收出现次数最多的那个值的字符名
String maxName = null;
// 定义一个计数用的变量
int count = 0;
// 循环判断指定字符串中包不包含某单个字符,包含就将字符名和出现的次数一起保存进TreeMap中.
for (int i = 0; i < str.length(); i++) {
count = 0;
s = str.charAt(i) + "";
pattern = Pattern.compile(s);
matcher = pattern.matcher(str);
while (matcher.find()) {
count++;
}
treeMap.put(s, count);
}
// 然后开始迭代TreeMap中已经存在的记录,从而求得出现次数最大的那个字符和它的名字.
iterator = treeMap.entrySet().iterator();
while (iterator.hasNext()) {
next = iterator.next();
// 只要每次迭代取出的次数的值大于当前出现次数最多的值max,那么就将迭代出来的值赋给
// max,将迭代出来的名字赋给maxName,然后打印出结果,功能就宣告成功实现
if (next.getValue() > max) {
max = next.getValue();
maxName = next.getKey();
}
System.out.println(next.getKey() + " -> " + next.getValue());
}
System.out.println("出现次数最多的字符是: " + maxName + ", 一共出现了: " + max + "次.");
// 最后用户使用不使用返回的TreeMap对象,这个不硬性规定,由用户自主选择,建议最好是使用返回
// 的值,这样更符合面向对象的思想.
return treeMap;
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2