在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
1 # -*- coding:utf-8 -*- 2 from collections import OrderedDict 3 class Solution: 4 def FirstNotRepeatingChar(self, s): 5 n = len(s) 6 if n == 0: 7 return -1 8 if n == 1: 9 return -1 10 dic = OrderedDict() 11 for c in s: 12 if c in dic: 13 dic[c] += 1 14 else: 15 dic[c] = 1 16 for i in range(n): 17 if dic[s[i]] == 1: 18 return i 19 return -1 20 # write code here
Java版代码,leetcode地址:
1 class Solution { 2 public char firstUniqChar(String s) { 3 HashMap<Character, Integer> mapTimes = new HashMap<Character, Integer>(); 4 HashMap<Character, Integer> mapIndex = new HashMap<Character, Integer>(); 5 int n = s.length(); 6 char[] ary = s.toCharArray(); 7 for (int i = 0; i < n; i++) { 8 char c = s.charAt(i); 9 10 // 判断是否存在于mapTimes 11 if (mapTimes.containsKey(c)) { 12 int times = mapTimes.get(c).intValue(); 13 times++; 14 mapTimes.put(c, times); 15 } else { 16 mapTimes.put(c, 1); 17 } 18 19 // 判断是否存在于mapIndex 20 if (!mapIndex.containsKey(c)) { 21 mapIndex.put(c, i); 22 } 23 } 24 int minIndex = n; 25 for (Character key : mapTimes.keySet()) { 26 if (mapTimes.get(key).intValue() == 1) { 27 int index = mapIndex.get(key).intValue(); 28 minIndex = Integer.min(minIndex, index); 29 } 30 } 31 if (minIndex == n) { 32 return ' '; 33 } else { 34 return s.charAt(minIndex); 35 } 36 } 37 }
Java第二种写法,使用LinkedHashMap实现:
1 class Solution { 2 public char firstUniqChar(String s) { 3 LinkedHashMap<Character, Integer> map = new LinkedHashMap<>(); 4 int n = s.length(); 5 char[] ary = s.toCharArray(); 6 for (int i = 0; i < n; i++) { 7 char c = s.charAt(i); 8 9 // 判断是否存在于mapTimes 10 if (map.containsKey(c)) { 11 int times = map.get(c).intValue(); 12 times++; 13 map.put(c, times); 14 } else { 15 map.put(c, 1); 16 } 17 } 18 for(Map.Entry<Character, Integer> entry : map.entrySet()) { 19 if(entry.getValue()==1) { 20 return entry.getKey(); 21 } 22 } 23 return ' '; 24 } 25 }