日期:2014-05-20 浏览次数:20800 次
String str = "1122345678"; HashMap<Character, Integer> strhash = new HashMap<Character, Integer>(); int num = 0; int count = 0; for (int i = 0; i <= str.length() - 1; i++) { char c = str.charAt(i); int temp = 0; for (int j = 0; j <= str.length() - 1; j++) { num = str.indexOf(c, temp); if (num != -1) { count++; temp = num + 1; continue; } else { strhash.put(c, count); count = 0; break; } } } Iterator iter1 = strhash.keySet().iterator(); while (iter1.hasNext()) { Object key = iter1.next(); Object value = strhash.get(key); System.err.println(key + " 的出现次数为:" + value+" 次"); }
------解决方案--------------------
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Scanner; import java.util.Set; public class ShowNum { public static void main(String[] args) { Map<String, Integer> m = new HashMap<String, Integer>(); boolean test = true; String str = ""; for (int i = 0; i < 10; i++) { Scanner sc = new Scanner(System.in); if(sc.hasNext()) { str = sc.next(); Set<String> set = m.keySet(); Iterator<String> it = set.iterator(); label: while (it.hasNext()) { String s = it.next(); if (s.equals(str)) { int n = m.get(s); it.remove(); m.remove(s); m.put(str, n + 1); test = false; break label; } } } if (test) { m.put(str, 1); //str出现的第一次 test=true; } } System.out.println(m); } }
------解决方案--------------------
import java.util.*;
public class Statistics {
public static void main(String[] args){
Random rand=new Random(100);
List<Integer> list=new ArrayList<Integer>();
Map<Integer,Integer> hm=new HashMap<Integer,Integer>();
for(int i=0;i<10;i++)
list.add(rand.nextInt(5));
System.out.println(list);
for(Integer it:list){
Integer freq=hm.get(it);
hm.put(it,freq==null?1:freq+1 );
}
System.out.println(hm);
}
}
结果:[0, 0, 4, 3, 1, 1, 1, 3, 3, 3]
{0=2, 1=3, 3=4, 4=1}
------解决方案--------------------
给你个简单的算法,用数组。
如果给的数范围不是超大的话。
int a[SIZE];
将数组a全部初始化0;
for(...)
{
a[i]++; //i就是你出现的数 a[i]就是次数
}
懂没?
------解决方案--------------------
public class Zygcsmb { public static void main(String[] args) { String str = "11223451627138",strsave = ""; char[] xx = str.toCharArray(); Arrays.sort(xx); StringBuffer sb = new StringBuffer(); sb.append(xx); str = sb.toString(); for(int i = 0; i<str.length(); i ++){ if(!strsave.equals(""+str.charAt(i))){ strsave = String.valueOf(str.charAt(i)); System.out.print(str.charAt(i)+"出现次数:"); System.out.println(str.lastIndexOf(str.charAt(i))-str.indexOf(str.charAt(i))+1); } } } } 运行结果: 1出现次数:4 2出现次数:3 3出现次数:2 4出现次数:1 5出现次数:1 6出现次数:1 7出现次数:1 8出现次数:1