给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -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'))

 

相关文章:

  • 2021-11-17
  • 2022-12-23
  • 2022-02-02
  • 2022-01-11
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-09
猜你喜欢
  • 2021-09-01
  • 2022-03-06
  • 2021-09-27
  • 2021-08-08
  • 2022-01-28
  • 2021-06-26
  • 2021-06-30
相关资源
相似解决方案