给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
s = "leetcode" 返回 0. s = "loveleetcode", 返回 2.
class solution: def getChar(self,s): setS = set(s) dict = {} for i in setS: dict[i] = s.count(i) #该方法返回子字符串在字符串中出现的次数。 for index,value in enumerate(s): print('j'+str(index)+' , k'+str(value)) if dict.get(value) == 1: return index return -1 def getChar2(self,s): return min([s.find(c) for c in 'abcdefghijklmnopqrstuvwxyz' if s.count(c)==1] or [-1]) if __name__ == "__main__": solution = solution() index = solution.getChar('leetcode') index2 = solution.getChar('loveleetcode') print(index) print(index2) print(solution.getChar2('leetcode')) print(solution.getChar2('loveleetcode'))