62,621
社区成员
发帖
与我相关
我的任务
分享 public static void main(String[] args) {
String input = "\"hello world\"";
int[] result = new int[128];
boolean firstTime = true;
for (char c : input.toCharArray()) {
result[c]++;
if (firstTime && result[c] > 1) {
System.out.printf("first repeat character:%c\n", c);
firstTime = false;
}
}
for (int i = 0; i < result.length; i++) {
if (result[i] > 1) {
System.out.printf("repeat character:%c,tims:%d.\n", (char) i, result[i]);
}
}
}
[/quote]
java8 666.
char[] chars = "hello world".toCharArray();
Map<Character, Integer> mappingCount = new HashMap<>();
LinkedList<Character> repeatedChars = new LinkedList<>();
for(char c : chars){
mappingCount.computeIfPresent(Character.valueOf(c), (k, v) -> {repeatedChars.offer(c); return v + 1;});
mappingCount.putIfAbsent(Character.valueOf(c), 1);
}
System.out.println(mappingCount);
System.out.println("first repeated character: " + repeatedChars.poll());
char[] chars = "hello world".toCharArray();
Map<Character, Integer> mappingCount = new HashMap<>();
for(char c : chars){
mappingCount.merge(Character.valueOf(c), 1, (oldV, newV) -> oldV + 1);
}
System.out.println(mappingCount);
char[] chars = "hello world".toCharArray();
Map<Character, Integer> mappingCount = new HashMap<>();
for(char c : chars){
mappingCount.computeIfPresent(Character.valueOf(c), (k,v) -> v +1);
mappingCount.putIfAbsent(Character.valueOf(c), 1);
}
System.out.println(mappingCount);

public static void main(String[] args) {
Map<Character, Integer> map = new HashMap<>();//创建一个map<字母,出现次数>
Character first=null;//创建一个char对象代表第一个出现重复的
String a= "hello world";
char[] charArray = a.trim().toCharArray();//获取字符串里所有字符
for (char c : charArray) { //循环字符数组
Integer num = map.get(c);//从map里获取次数,如为null,带表第一次出现
if (num==null) {
num=1;
}else{
if (first==null) {//如果不为空且上面声明的first对象为空,则是第一个出现重复的字母,将次数+1
first=c;
}
num++;
}
map.put(c, num);
}
for (char c : map.keySet()) {
Integer num = map.get(c);
if (num>1) { //次数大于1代表重复,打印出来
System.out.println("字母"+c+"重复出闲"+map.get(c)+"次!");
}
}
System.out.println("第一个重复的字母是:"+first);
}