题目:字符串中的第一个唯一字符
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
难度:简单
示例:
s = “leetcode”
返回 0
s = “loveleetcode”
返回 2
提示:你可以假定该字符串只包含小写字母。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string
著作权归领扣网络所有。商业转载请联系官方获得授权,非商业转载请注明出处。
解题思路
- 使用哈希表存储频数
- 使用哈希表存储索引
- 队列
解题代码
使用哈希表存储频数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Solution { public int firstUniqChar(String s) { HashMap<Character,Integer> hashMap = new HashMap<>(); char[] c = s.toCharArray(); for (int i = 0; i < c.length; i++){ hashMap.put(c[i],hashMap.getOrDefault(c[i],0) + 1); } for (int i = 0; i < c.length; i++){ if (hashMap.get(c[i]) == 1){ return i; } } return -1; } }
|
官方解题代码
使用哈希表存储频数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Solution { public int firstUniqChar(String s) { Map<Character, Integer> frequency = new HashMap<Character, Integer>(); for (int i = 0; i < s.length(); ++i) { char ch = s.charAt(i); frequency.put(ch, frequency.getOrDefault(ch, 0) + 1); } for (int i = 0; i < s.length(); ++i) { if (frequency.get(s.charAt(i)) == 1) { return i; } } return -1; } }
|
使用哈希表存储索引
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| class Solution { public int firstUniqChar(String s) { Map<Character, Integer> position = new HashMap<Character, Integer>(); int n = s.length(); for (int i = 0; i < n; ++i) { char ch = s.charAt(i); if (position.containsKey(ch)) { position.put(ch, -1); } else { position.put(ch, i); } } int first = n; for (Map.Entry<Character, Integer> entry : position.entrySet()) { int pos = entry.getValue(); if (pos != -1 && pos < first) { first = pos; } } if (first == n) { first = -1; } return first; } }
|
队列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Solution { public int firstUniqChar(String s) { Map<Character, Integer> position = new HashMap<Character, Integer>(); Queue<Pair> queue = new LinkedList<Pair>(); int n = s.length(); for (int i = 0; i < n; ++i) { char ch = s.charAt(i); if (!position.containsKey(ch)) { position.put(ch, i); queue.offer(new Pair(ch, i)); } else { position.put(ch, -1); while (!queue.isEmpty() && position.get(queue.peek().ch) == -1) { queue.poll(); } } } return queue.isEmpty() ? -1 : queue.poll().pos; }
class Pair { char ch; int pos;
Pair(char ch, int pos) { this.ch = ch; this.pos = pos; } } }
|