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.
Note: You may assume the string contain only lowercase letters.
class Solution(object): def firstUniqChar(self, s): """ :type s: str :rtype: int """ cnt = collections.Counter(s) for i,c in enumerate(s): if cnt[c] == 1: return i return -1
java 里还可以,直接一次扫描s搞定:
class Solution { public int firstUniqChar(String s) { Map<Character, Integer> map = new LinkedHashMap<>(); Set<Character> set = new HashSet<>(); for (int i = 0; i < s.length(); i++) { if (set.contains(s.charAt(i))) { if (map.get(s.charAt(i)) != null) { map.remove(s.charAt(i)); } } else { map.put(s.charAt(i), i); set.add(s.charAt(i)); } } return map.size() == 0 ? -1 : map.entrySet().iterator().next().getValue(); } }
因为map里entryset保存了add顺序???