标签:
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