題目描述
在一個字符串(0<=字符串長度<=10000,全部由字母組成)中找到第一個只出現一次的字符,並返回它的位置, 如果沒有則返回 -1(需要區分大小寫).
# -*- 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