黑马程序员技术交流社区
标题:
TreeMap字符串中字符出现次数练习
[打印本页]
作者:
itheima_llt
时间:
2015-4-19 11:57
标题:
TreeMap字符串中字符出现次数练习
本帖最后由 itheima_llt 于 2015-4-19 11:58 编辑
/*
练习:
"sdfgzxcvasdfxcvdf"获取该字符串中的字母出现的次数。
希望打印结果:a(1)c(2).....
通过结果发现,每一个字母都有对应的次数。
说明字母和次数之间都有映射关系。
注意了,当发现有映射关系时,可以选择map集合。
因为map集合中存放就是映射关系。
什么使用map集合呢?
当数据之间存在这映射关系时,就要先想map集合。
思路:
1,将字符串转换成字符数组。因为要对每一个字母进行操作。
2,定义一个map集合,因为打印结果的字母有顺序,所以使用treemap集合。
3,遍历字符数组。
将每一个字母作为键去查map集合。
如果返回null,将该字母和1存入到map集合中。
如果返回不是null,说明该字母在map集合已经存在并有对应次数。
那么就获取该次数并进行自增。,然后将该字母和自增后的次数存入到map集合中。覆盖调用原键所对应的值。
4,将map集合中的数据变成指定的字符串形式返回。
*/
import java.util.*;
public class TreeMapStringTest
{
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args)
{
//1 创建一个字符串对象
String str = new String("akabAf3+22*-cdCkaAbcdefa");
//打印目标字符串
sop("被访问的字符串:"+str);
//2 获取字符串中每个字母出现的次数,以指定字符串的形式返回
sop("每个字母出现的次数:"+getCharCount(str));
}
//定义方法获取字符串中每个字母出现的次数,以指定字符串的形式返回
public static String getCharCount(String str)
{
//1 把字符串变成字符数组
char[] chs = str.toCharArray();
//2 创建TreeMap映射
TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
//3 遍历字符数组,计算每个字母出现的次数,并存入TreeMap
traverseArray_2(tm,chs);
//用StringBuilder存储指定字符串
StringBuilder sb = new StringBuilder();
//4 将Treemap映射中的键值取出来,以指定字符串的形式返回
return getKeyValue(tm,sb);
}
//3.1优化前: 定义方法:遍历字符数组,计算每个字母出现的次数,并存入TreeMap
public static void traverseArray(TreeMap<Character,Integer> tm,char[] chs)
{
int count = 0;
for(int i = 0;i < chs.length; i++)
{
//如果不是字母则跳过
if(!(chs[i] >='a' && chs[i] <= 'z'|| chs[i] >= 'A' && chs[i] <= 'Z'))
continue;
if(tm.get(chs[i])==null)
{
count = 1;
tm.put(chs[i],count);
}
else
{
count = tm.get(chs[i]);
count++;
tm.put(chs[i],count);
}
count = 0;
}
}
//3.2优化后 定义方法:遍历字符数组,计算每个字母出现的次数,并存入TreeMap
public static void traverseArray_2(TreeMap<Character,Integer> tm,char[] chs)
{
int count = 0;
for(int i = 0;i < chs.length; i++)
{
//如果不是字母则跳过
if(!(chs[i] >='a' && chs[i] <= 'z'|| chs[i] >= 'A' && chs[i] <= 'Z'))
continue;
//优化代码
if(tm.get(chs[i]) != null)
count = tm.get(chs[i]);
count++;
tm.put(chs[i],count);//直接往集合中存储字符和数字,为什么可以,因为自动装箱。
count = 0;
}
}
//4.1 第一种方式: 将Treemap映射中的键值取出来,以指定字符串的形式返回
public static String getKeyValue(TreeMap<Character,Integer> tm,StringBuilder sb)
{
Set<Character> keySet = tm.keySet();
for(Iterator<Character> it = keySet.iterator(); it.hasNext(); )
{
Character ch = it.next();
Integer i = tm.get(ch);
sb.append(ch+"("+i+")");
}
return sb.toString();
}
//4.2 第二种方式: 将Treemap映射中的键值取出来,以指定字符串的形式返回
public static String getKeyValue_2(TreeMap<Character,Integer> tm,StringBuilder sb)
{
//第二种方式取出所有键值
Set<Map.Entry<Character,Integer>> entry = tm.entrySet();
for(Iterator<Map.Entry<Character,Integer>> it = entry.iterator(); it.hasNext(); )
{
Map.Entry<Character,Integer> me = it.next();
Character ch = me.getKey();
Integer i = me.getValue();
sb.append(ch+"("+i+")");
}
return sb.toString();
}
}
复制代码
TreeMap字符串次数演示.jpg
(49.97 KB, 下载次数: 16)
下载附件
2015-4-19 11:58 上传
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2