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

How to find First Non-Repeated Character from String

时间:2016-08-22 18:02:14      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:

You need to write a function, which will accept a String and return first non-repeated character, for example in the world "hello", except ‘l‘ all are non-repeated, but ‘h‘ is the first non-repeated character. Similarly, in word "swiss" ‘w‘ is the first non-repeated character. One way to solve this problem is creating a table to store count of each character, and then picking the first entry which is not repeated. The key thing to remember is order, your code must return first non-repeated letter.

 1 public class solution {
 2     public char firstNonRepeating(String s) {
 3         char result = ‘#‘;
 4         if (s == null || s.length == 0) {
 5             return result;
 6         }
 7         Map<Character,Integer> map = HashMap<>();
 8         for (int i = 0; i < s.length(); i++) {
 9             if (map.containsKey(s.charAt(i))) {
10                 map.put(s.charAt(i), map.get(s.charAt(i)) + 1);
11             } else {
12                 map.put(s.charAt(i), 1);
13             }
14         }
15 
16         for (int i = 0; i < s.length; i++) {
17             if (map.get(s.charAt(i) == 1)) {
18                 result = s.charAt(i);    
19                 return result;
20             }
21         }
22         return result; 
23     }
24 }

 

How to find First Non-Repeated Character from String

标签:

原文地址:http://www.cnblogs.com/FLAGyuri/p/5796263.html

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