KK's blog

每天积累多一些

0%

LeetCode 387 First Unique Character in a String

LeetCode



Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

Example 1:

Input: s = “leetcode”
Output: 0


Example 2:

Input: s = “loveleetcode”
Output: 2


Example 3:

Input: s = “aabb”
Output: -1


Constraints:

1 <= s.length <= 10<sup>5</sup> s consists of only lowercase English letters.

题目大意:

求字符串中第一个唯一的字符下标

解题思路:

Easy题。先统计频率,然后再遍历一次字符串找到频率为1的字符

解题步骤:

N/A

注意事项:

  1. Python代码:

    1
    2
    3
    4
    5
    6
    def firstUniqChar(self, s: str) -> int:
    char_to_count = collections.Counter(s)
    for i in range(len(s)):
    if char_to_count[s[i]] == 1:
    return i
    return -1

算法分析:

时间复杂度为O(n),空间复杂度O(1), 26个字母为常量空间

Free mock interview