[LeetCode] 387.字符串中的第一个唯一字符(Easy)C语言题解

题目

  • 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

示例

①示例1

  • s = “leetcode”
  • 返回 0.

②示例2

  • s = “loveleetcode”,
  • 返回 2.

说明

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

①相关话题

  • 哈希表

②相似题目

  • 451. 根据字符出现频率排序 — 力扣网
  • 451. Sort Characters By Frequency — leetcode

③题目地址

  • 387. 字符串中的第一个唯一字符 — 力扣网
  • 387. First Unique Character in a String — leetcode

解题方法

①哈希表

  • 可用数组模拟的哈希表求解,速度最快(用空间换时间)。
  • 用哈希表记录每个字母的出现次数,然后寻找第一个唯一字符即可。
  • 时间复杂度:O(N)。
  • 空间复杂度:O(N)。

代码详解

  • 哈希表
int firstUniqChar(char* s) {
    int hash[26] = {0}, i, len = strlen(s);
    
    // 用哈希表记录每个字母的出现次数。
    for (i = 0; i < len; i++)
        hash[s[i]-'a']++;
    // 寻找第一个唯一字符。
    for (i = 0; i < len; i++) {
        if (hash[s[i]-'a'] == 1)
            break;
    }
    
    return i == len? -1: i;
}

附录

  • 我的个人博客:messi1002.top
  • 如有错误或疑惑之处 请联系 [email protected]
  • 所有题目解答:fork me on github

你可能感兴趣的:(LeetCode-C,LeetCode-C)