(python)小菜狗算法日记(字符串系列)

    技术2022-07-13  85

    题目描述

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

    思路一: 利用字符串的切片,用find函数查找去掉当前字符后的字符串是否包含当前字符

    # -*- coding:utf-8 -*- class Solution: def FirstNotRepeatingChar(self, s): # write code here for i in range(len(s)): tmp = s[:i]+s[i+1:] if tmp.find(s[i])==-1: return i return -1

    思路二,与思路一类似,去掉跟当前字符相同的所有字符,查看去掉后的长度,是否为原字符串长度减一

    # -*- coding:utf-8 -*- class Solution: def FirstNotRepeatingChar(self, s): # write code here if not s: return -1 index = 0 for a in s: if len(s.replace(a,''))==len(s)-1: return index index+=1

     

    Processed: 0.013, SQL: 9