剑指offer -第一个只出现一次的字符位置 - python

124 阅读1分钟

题目描述:

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

思路:

  • 法1: 首先找到字符串中出现过的字符,然后依次在字符串中进行查找直到找到第一个只出现一次的字符,返回它在字符串中的索引。
  • 法2: 使用dict来记录 s s s中字符和对应的数量,最后遍历dict找到数量为1的字符在 s s s中的索引即可。

AC代码

法1

# -*- coding:utf-8 -*-
class Solution:
    def FirstNotRepeatingChar(self, s):
        # write code here
        if len(s) == 0:
        	return None
        	
        set_s = list(set(s))
        set_s.sort(key = s.index)
        
        for i in set_s:
            count = 0
            for id in range(len(s)):
                if i == s[id]:
                    count += 1
            if count > 1:
            	continue
            else:
            	return s.index(i)
            
        return -1

法2:我在编译器中可以得到正确答案,但是提交却出现错误,懵了,难道是python版本的区别?有知道哪里出错的朋友可以评论告诉我,谢谢~

# -*- coding:utf-8 -*-
class Solution:
    def FirstNotRepeatingChar(self, s):
        # write code here
        if len(s) == 0:
            return None

        strNum = {}
        for i in s:
            if i not in strNum.keys():
                strNum[i] = 1
            else:
                num = strNum.get(i)
                strNum[i] = num + 1

        for c, n in strNum.items():
            if n == 1:
                return s.index(c)

        return None

s = Solution()
ss = 'google'
sss = 'NXWtnzyoHoBhUJaPauJaAitLWNMlkKwDYbbigdMMaYfkVPhGZcrEwp'
print(s.FirstNotRepeatingChar(sss))

"""
D:\data\Code>python test.py
string is:  google
first char index  is:  4
string is:  NXWtnzyoHoBhUJaPauJaAitLWNMlkKwDYbbigdMMaYfkVPhGZcrEwp
first char index  is:  1
"""