来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string

描述

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = “leetcode”
返回 0.

s = “loveleetcode”,
返回 2.

注意事项:您可以假定该字符串只包含小写字母。

题解

  1. class Solution {
  2. public int firstUniqChar(String s) {
  3. HashMap<Character, Integer> count = new HashMap<>();
  4. int n = s.length();
  5. for (int i = 0; i < n; i++) {
  6. char c = s.charAt(i);
  7. count.put(c, count.getOrDefault(c, 0) + 1);
  8. }
  9. for (int i = 0; i < n; i++) {
  10. if (count.get(s.charAt(i)) == 1) {
  11. return i;
  12. }
  13. }
  14. return -1;
  15. }
  16. }

复杂度分析:

  • 时间复杂度:387. 字符串中的第一个唯一字符(First Unique Character in a String) - 图1,遍历了两遍字符串,同时散列表中查找操作是常数时间复杂度的。
  • 空间复杂度:387. 字符串中的第一个唯一字符(First Unique Character in a String) - 图2,用到了散列表来存储字符串中每个元素出现的次数。