carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode387:字符串中的第一个唯一字符(first-unique-character-in-a-string) #88

Open carloscn opened 1 year ago

carloscn commented 1 year ago

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

示例 1: 输入: s = "leetcode" 输出: 0

示例 2: 输入: s = "loveleetcode" 输出: 2

示例 3: 输入: s = "aabb" 输出: -1   提示: 1 <= s.length <= 105 s 只包含小写字母

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

carloscn commented 1 year ago

问题分析

遍历字符串,二级遍历字符串,如果相等且不等于当前位置的字符,就break。如果二级遍历因子能够到字符串长度,说明是满足要求的字符。

static int32_t first_char(char *str, size_t *index)
{
    char e = 0;
    size_t i = 0;
    size_t j = 0;
    size_t len = 0;
    int32_t ret = 0;

    UTILS_CHECK_PTR(str);
    UTILS_CHECK_PTR(index);
    UTILS_CHECK_LEN(len = strlen(str));

    *index = 0xffff;

    for (i = 0; i < len; i ++) {
        e = str[i];
        for (j = 0; j < len; j ++) {
            if (e == str[j] && i != j) {
                break;
            }
        }
        if (j == len) {
            *index = i;
            break;
        }
    }

finish:
    return ret;
}
carloscn commented 1 year ago

code:

https://github.com/carloscn/structstudy/blob/master/c_programming/str/20_first-unique-character-in-a-string_387.c

result:

image