劍指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
相關文章
相關標籤/搜索