码迷,mamicode.com
首页 > 其他好文 > 详细

求仅出现一次的最早字符

时间:2017-07-09 21:54:37      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:lin   题目   set   层遍历   cin   array   move   result   lis   

题目

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

例如输入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     }

 

求仅出现一次的最早字符

标签:lin   题目   set   层遍历   cin   array   move   result   lis   

原文地址:http://www.cnblogs.com/sachen/p/7102499.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!