跳转至

387. 字符串中的第一个唯一字符

最后更新:2024-05-10-22

链接:https://leetcode.cn/problems/first-unique-character-in-a-string/description/

题目描述

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

题目示例

输入: s = "leetcode"

输出: 0

输入: s = "loveleetcode"

输出: 2

输入: s = "aabb"

输出: -1

提示:

  • \(1 <= s.length <= 10^5\)
  • s 只包含小写字母

解题思路

使用字符串函数,从前往后和从后往前找到的第一个索引如果是一样的,说明是唯一的。

C
int firstUniqChar(char * s){
    for (int i = 0; i < strlen(s); i++) {
        char* first = strchr(s,s[i]);
        char* flow = strrchr(s,s[i]);

        if (first == flow) {
            return i;
        }
    }

    return -1;
}
Go