1. 程式人生 > >劍指offer——第一個只出現一次的字元

劍指offer——第一個只出現一次的字元

這個題在劍指offer裡屬於常規題,主要看程式語言的運用的如何巧。 python 常規操作,用count計數,index輸出位置

class Solution():
	def FirstNotRepeatingChar(self,s):
		if len(s)<1:return -1
		for i in s:
			if s.count(i)==1:
				return s.index(i)
				break
		return -1

大神壓縮,一行Python程式碼搞定

class Solution():
	def FirstNotRepeatingChar(self,s):
		return [i for i in range(len(s))  if s.count(s[i])==1][0] if s else -1

採用內建函式

class Solution():
	def FirstNotRepeatingChar(self,s):
		return s.index(list(filter(lambda c:s.count(c)==1,s)[0]) if s else -1

使用雜湊表

class  Solution():
	def FirstNotRepeatingChar(self,s):
	 	Is=[0]*256
	 	for i in s:
	 		ls[ord[i]]+=1
	 	for j in s:
	 		if ls[ord[j]]==1:
	 			return s.index(j)
	 			break
	 	return -1