在一个长为 字符串中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数)
数据范围:,且字符串只有字母组成。
要求:空间复杂度 ,时间复杂度
class Solution: def FirstNotRepeatingChar(self , str: str) -> int: # write code here times = dict() que = list() for item in str: times[item] = times.get(item, 0) +1 if item not in que and times[item]==1: que.append(item) elif item in que: que.remove(item) else: pass return str.index(que[0]) if len(que)>0 else -1
class Solution: def FirstNotRepeatingChar(self , str: str) -> int: # write code here if not str: return -1 white_list = [] black_list = [] for s in str: if s not in black_list: if s not in white_list: white_list.append(s) else: white_list.remove(s) black_list.append(s) return str.index(white_list[0]) if white_list else -1
class Solution: # 哈希表 # 时间复杂度:O(n) 空间复杂度:O(1) def FirstNotRepeatingChar(self , str: str) -> int: mp = {} for i in str: if i in mp: mp[i] += 1 else: mp[i] = 1 n = -1 for i in str: n += 1 if mp[i] == 1: return n return -1
class Solution: # 哈希表 + 队列 # 时间复杂度:O(n) 空间复杂度:O(1) def FirstNotRepeatingChar(self , str: str) -> int: mp = {} q1 = [] q2 = [] for i in range(len(str)): # 没有出现过的字符 if str[i] not in mp: mp[str[i]] = i # 记录位置 q1.append(str[i]) q2.append(i) # 找到重复字符 else: # 重复标记位置记为-1 mp[str[i]] = -1 # 弹出前面所有的重复过的字符 while len(q1) != 0 and mp[q1[0]] == -1: q1.pop(0) q2.pop(0) return -1 if len(q2) == 0 else q2[0]
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param str string字符串 # @return int整型 # class Solution: def FirstNotRepeatingChar(self , string: str) -> int: # write code here arr=[0]*len(string) for i in range(len(string)): for j in range(i+1,len(string)): if string[i]==string[j]: arr[i]=arr[i]+1 arr[j]=arr[j]+1 for i in range(len(arr)): if arr[i]==0: return i return -1
class Solution: def FirstNotRepeatingChar(self , str: str) -> int: # write code here # 记录字符的次数 d = {} for ch in str: d[ch] = d.get(ch, 0) + 1 res = [] # 记录出现1次的字符的位置 for ch in d: if d[ch] == 1: res.append(str.index(ch)) if len(res) == 0: return -1 return min(res)
class Solution: def FirstNotRepeatingChar(self , str: str) -> int: # write code here d = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' # d = set(str) pos = -1 for c in d: if str.count(c) == 1: idx = str.index(c) if pos == -1&nbs***bsp;pos > idx: pos = idx return pos
class Solution: def FirstNotRepeatingChar(self , strs: str) -> int: # write code here l = len(strs) if l == 0: return -1 elif l == 1: return strs[0] dic = {} for i in range(l): dic[strs[i]] = [0,i] for i in range(l): dic[strs[i]][0] += 1 for k,v in dic.items(): if v[0] == 1: return v[1] return -1
# 哈希表 class Solution: def FirstNotRepeatingChar(self, s): # write code here hashTable = [-1] * 52 for i, ch in enumerate(s): if ch < 'a': tmp = ord(ch) - ord('A') else: tmp = ord(ch) - ord('a') + 26 if hashTable[tmp] >= 0: hashTable[tmp] = -2 else: hashTable[tmp] = i minI = len(s) for i in hashTable: if i >= 0 and minI > i: minI = i if minI == len(s): return -1 return minI