记录刷题的过程。牛客和力扣中都有相关题目,这里以牛客的题目描述为主。该系列默认采用python语言。
1、问题描述:
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数)
2、数据结构:
哈希表
3、题解:
构造哈希表,先遍历一次,把没有重复的value置为True,把有重复的置为False。
然后遍历,第一次value为True的下标就是要找的;如果遍历完没有,则返回-1.
# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
dict1 = {}
for c in s:
dict1[c] = not c in dict1
for i in range(len(s)):
if dict1[s[i]] :
return i
return -1或者:下面这种可能更好理解
# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
dict1 = {}
for c in s:
if c in dict1:
dict1[c] = 0
else :
dict1[c] = 1
#dict1[c] = not c in dict1
for i in range(len(s)):
if dict1[s[i]] :
return i
return -14、复杂度分析:
时间复杂度都为O(N)
空间复杂度都为O(N)
版权声明:本文为weixin_42042056原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。