carloscn / structstudy

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

leetcode2351: First Letter to Appear Twice #385

Open carloscn opened 11 months ago

carloscn commented 11 months ago

Description

Given a string s consisting of lowercase English letters, return the first letter to appear twice.

Note:

A letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b. s will contain at least one letter that appears twice.

Example 1:

Input: s = "abccbaacz" Output: "c" Explanation: The letter 'a' appears on the indexes 0, 5 and 6. The letter 'b' appears on the indexes 1 and 4. The letter 'c' appears on the indexes 2, 3 and 7. The letter 'z' appears on the index 8. The letter 'c' is the first letter to appear twice, because out of all the letters the index of its second occurrence is the smallest.

Example 2:

Input: s = "abcdd" Output: "d" Explanation: The only letter that appears twice is 'd' so we return 'd'.

Constraints:

2 <= s.length <= 100 s consists of lowercase English letters. s has at least one repeated letter.

carloscn commented 11 months ago

Analysis

static int32_t repeated_character(char *s, char *out)
{
    int32_t ret = 0;
    size_t len;

    UTILS_CHECK_PTR(s);
    UTILS_CHECK_PTR(out);
    UTILS_CHECK_LEN(len = strlen(s));

    for (size_t i = 0; i < len - 1; i ++) {
        if (s[i] == s[i + 1]) {
            *out = s[i];
            goto finish;
        }
    }

finish:
    return ret;
}
carloscn commented 11 months ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1170821 https://github.com/carloscn/structstudy/commit/3aee62a81050b93d76e155498d3561cf4f704cef