剑指Offer 34. 第一个只出现一次的字符 (字符串)

时间:2023-11-21 23:55:32

题目描述

在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).

题目地址

https://www.nowcoder.com/practice/1c82e8cf713b4bbeb2a5b31cf5b0417c?tpId=13&tqId=11187&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

思路

两轮遍历

第一轮,使用hash表,记录各字符出现的次数

第二轮,当次数为1时,返回位置

Python

# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
if not s:
return -1
if len(s) == 1:
return 0
hash = {}
for i in range(len(s)):
if s[i] not in hash:
hash[s[i]] = 1
else:
hash[s[i]] += 1
for i in range(len(s)):
if hash[s[i]] == 1:
return i
return -1
if __name__ == '__main__':
result = Solution().FirstNotRepeatingChar('abcabcdef')
print(result)