在一個字符串(0<=字符串長度<=10000,全部由字母組成)中找到第一個只出現一次的字符,並返回它的位置, 如果沒有則返回 -1(需要區分大小寫)
解題思路:
第一:利用python特性
string.count(str) 返回 str 在 string 裏面出現的次數,利用python此特性可以幾行代碼搞定
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
if not s or len(s)<=0:
return -1
for i in s:
if s.count(i)==1:
return s.index(i)
return -1
第二:利用哈希表特性
自定義一個哈希表,利用每個字母的ASCII碼來作爲數組的index,用一個58長度的數組來存儲每個字母出現的次數,爲什麼是58呢,主要是由於A-Z對應的ASCII碼爲65-90,a-z對應的ASCII碼值爲97-122,而每個字母的index=int(word)-65,比如g=103-65=38,而數組中具體記錄的內容是該字母出現的次數,最終遍歷一遍字符串,找出第一個數組內容爲1的字母就可以了,時間複雜度爲O(n)。
class Solution(object):
def searchSingleChar(self, string):
list = []
for value in range(0, 58):
list.append(0)
for character in string:
count = list[ord(character) - 65]
list[ord(character) - 65] = count + 1
for index, character in enumerate(string):
if list[ord(character) - 65] == 1:
return index
obj = Solution()
characterIndex = obj.searchSingleChar('thisistestdemothisistestdemoX')
print("出現一次的第一個字母下標是: %d" % (characterIndex))