在Java面试中经常出现的算法题:
this is a cate and that is a mice and where is the food? 请统计每个单词出现的次数
通过Map来解决这个问题。
存储到Map中
Key:String
Value:自定义类型
* “分拣” 思路 * 思路1、为所有的key创建容器,之后容器中存放对应的value * 思路2、第一次创建容器,并存放值value * 第二次之后直接使用容器存放值
下面提供思路一的实例代码:
首先新建一个Letter类
public class Letter {
private String name;
private int count;
public Letter() {
}
public Letter(String name, int count) {
this.name = name;
this.count = count;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
package cn.zhouxj.map;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* this is a cate and that is a mice and where is the food?
* 统计每个单词出现的次数
*
* 存储到Map中
* Key:String
* Value:自定义类型
*
* “分拣” 思路
* 思路1、为所有的key创建容器,之后容器中存放对应的value
* 思路2、第一次创建容器,并存放值value
* 第二次之后直接使用容器存放值
**/
public class Demo01 {
public static void main(String[] args){
test01();
test02();
}
public static void test01(){
String str = "this is a cate and that is a mice and where is the food";
//第一步分割字符串
String[] strArray = str.split(" ");
//第二步存储到Map中,遍历数组
Map<String,Letter> letters = new HashMap<String,Letter>();
//思路1
/**
* 为所有的key创建容器,之后容器中存放对应的value
*/
//1、为所有的key创建容器
for(String temp:strArray){
if(!letters.containsKey(temp)){
letters.put(temp,new Letter());
}
//2、容器中存放对应的value
Letter col = letters.get(temp);//直接使用容器
col.setCount(col.getCount()+1);
}
//输出Map的值,Map的遍历。使用迭代器遍历keyset()
Set <String> keys = letters.keySet();
for(String key:keys){
System.out.println(key+": "+letters.get(key).getCount());
}
}
public static void test02(){
String str = "this is a cate and that is a mice and where is the food";
//第一步分割字符串
String[] strArray = str.split(" ");
//第二步存储到Map中,遍历数组
Map<String,Letter> letters = new HashMap<String,Letter>();
for(String temp:strArray){
if(!letters.containsKey(temp)){
Letter col = new Letter();
col.setCount(1);//第一次的值存放在容器中
letters.put(temp,col);
}else{
Letter col = letters.get(temp);//直接使用容器
col.setCount(col.getCount()+1);
}
}
//输出Map的值,Map的遍历。使用迭代器遍历keyset()
Set <String> keys = letters.keySet();
for(String key:keys){
System.out.println(key+": "+letters.get(key).getCount());
}
}
}
附录:
我自己的实现该算法的代码:
package cn.zhouxj.TestZhouxj;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* this is a cate and that is a mice and where is the food?
* 统计每个单词出现的次数
* */
public class TongJiWord {
public static void main(String[] args){
String str = "this is a cate and that is a mice and where is the food";
String[] str1 = str.split(" ");
Map<String,Integer> map = new HashMap<String,Integer>();
for(String temp:str1){
if(!map.containsKey(temp)){
map.put(temp,0);
}
if (map.containsKey(temp)){
Integer i = map.get(temp) + 1;
map.put(temp,i);
}
}
Set<String> set = map.keySet();
for(String temp:set){
System.out.println(temp+": "+map.get(temp));
}
}
}