华为java上机题目
题目:
手动输入一个字符串,仅限小写字母,统计并输出每个字符在字符串中出现的次数,并输出。提示可以用map
例子:输入:aaabbbccc
输出:a 3
b 3
c 3
分析: 看到后面的提示,简直就是不用动脑,直接简单粗暴的顺势而上
直接上代码:
package com.javaer.huawei;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class TestCharAcount {
public static void main(String args[]) {
String strIn = "aaabbbccc";
TestCharAcount tc = new TestCharAcount();
Map mTemp = tc.charAcount(strIn);
Set ks = mTemp.keySet();// 生成索引set
for (Iterator it = ks.iterator(); it.hasNext();) {// 遍历索引取值
char c = it.next();
System.out.println(c + " " + mTemp.get(c));
}
}
public Map charAcount(String strIn) {
String tempStr = strIn;
// The map is sorted according to the natural ordering of its keys
// treemap是以键的自然顺序来存储值的
Map m = new TreeMap();
char[] strC = tempStr.toCharArray();
for (int i = 0; i < strC.length; i++) {
Integer count = m.get(strC[i]);
if (null == count)
count = 0;
count++;
m.put(strC[i], count);
}
return m;
}
}
You must be logged in to post a comment.
这些题以前都做过的