题目描述
找出字符串中第一个只出现一次的字符
输入描述
输入一串字符
输出描述
输出一个字符
输入例子
asdfasdfo
输出例子
o
算法实现
import java.util.*;
/**
* Author: 王俊超
* Date: 2015-12-24 15:59
* All Rights Reserved !!!
*/
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String input = scanner.nextLine();
System.out.println(findFirst(input));
}
scanner.close();
}
private static char findFirst(String s) {
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (map.containsKey(c)) {
map.put(c, Integer.MAX_VALUE);
} else {
map.put(c, i);
}
}
Collection<Integer> set = map.values();
int min = Integer.MAX_VALUE;
for (int i : set) {
if (min > i) {
min = i;
}
}
return min == Integer.MAX_VALUE ? '.' : s.charAt(min);
}
}