剑指offer:第一个只出现一次的字符

题目描述
在一个字符串(0<=字符串长度<=10000,所有由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 若是没有则返回 -1(须要区分大小写).python

# -*- coding: utf-8 -*-
# @Time         : 2019-07-12 9:40
# @Author       : Jayce Wong
# @ProjectName  : job
# @FileName     : firstNotRepeatingChar.py
# @Blog         : https://blog.51cto.com/jayce1111
# @Github       : https://github.com/SysuJayce

from collections import defaultdict

class Solution:
    """
    因为这道题目和次数有关,所以有两种解法。
    解法1:
    遍历字符串,对于当前字符,遍历后面的全部字符,若是出现了相同的字符,那么说明这个字符出现次数>1
    这种解法的时间复杂度为O(n^2)

    解法2:
    维护一个哈希表,用于保存每一个字符出现的次数。这样,经过两轮遍历,第一轮统计每一个字符的出现次数,
    第二轮查询每一个字符的出现次数,若是次数为1那么就返回该字符的下标。
    这种解法的时间复杂度为O(n)
    """
    def FirstNotRepeatingChar(self, s):
        if not s:
            return -1

        # 在python中,咱们能够利用默认字典来简化代码
        char_count = defaultdict(int)
        for c in s:
            char_count[c] += 1

        for i in range(len(s)):
            if char_count[s[i]] == 1:
                return i
相关文章
相关标签/搜索