Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:
s = "leetcode" return 0. s = "loveleetcode", return 2.
分析:找出字符串中第一次出现且不重复的字符,返回其字符的下标,如果不存在就返回-1.
用hashMap进行求,hashMap中可以通过ey-value的存储位置对和位置,对数据进行标记
1 public int firstUniqChar(String s) { 2 Map<Character,Integer> map=new HashMap<Character,Integer>(); 3 4 for(int i=0;i<s.length();i++){ 5 char c=s.charAt(i); 6 if(map.containsKey(c)){ 7 map.put(c,-1); 8 }else{ 9 map.put(c,1); 10 } 11 } 12 13 for(int i=0;i<s.length();i++){ 14 if(map.get(s.charAt(i))==1){ 15 return i; 16 } 17 } 18 return -1; 19 }