求仅出现一次的最早字符

题目

请实现一个函数用来找出字符流中第一个只出现一次的字符。

例如输入google,输出l

代码

 1     private static Set<Character> filter = new HashSet<>();
 2     private static LinkedList<Character> result = new LinkedList<>();
 3 
 4     private static void getFirstChar(String string) {
 5         char[] chars = string.toCharArray();
 6         for (Character ch : chars) {
 7             if (!filter.contains(ch)) {
 8                 int cIndex = result.indexOf(ch);//避免使用contains底层遍历多次
 9                 if (cIndex == -1) {
10                     result.add(ch);
11                 } else {
12                     result.remove(cIndex);//复用
13                     filter.add(ch);
14                 }
15             }
16         }
17         System.out.println(result.size() == 0 ? "#" : result.getFirst());
18     }

上述是我写的代码,后来发现一个学弟写的更好,来贴一下,大家围观~~

 1     public static void findChar(String string) {
 2         char[] chars = new char[256];//所有字符--256,同时此处用char不用Int是为了减少空间
 3         for (int i = 0; i < string.length(); i++) {
 4             chars[string.charAt(i)]++;
 5         }
 6         for (int i = 0; i < string.length(); i++) {
 7             if (chars[string.charAt(i)] == 1) {
 8                 System.out.println(string.charAt(i));
 9                 break;
10             }
11             if (chars[string.charAt(i)] != 1 && i == string.length() - 1) {
12                 System.out.println("#");
13             }
14         }
15     }
原文地址:https://www.cnblogs.com/sachen/p/7102499.html