给出一个小写字符串's',返回在字符串中仅出现一次的第一个字符的索引

问题描述 投票:-1回答:2

“”“如果每个字符都出现多次,则返回-1。示例输入:s: "Who wants hot watermelon?。输出:8。”“”

def findLastIndex(str, x): 
    index = -1
    for i in range(0, len(str)): 
        if str[i] == x: 
            index = i 
    return index 

# String in which char is to be found 
str = "Who wants hot watermelon"

# char whose index is to be found 
x = 's'

index = findLastIndex(str, x) 

if index == -1: 
    print("Character not found") 
else: 
    print(index) 
python string lowercase
2个回答
0
投票

尝试一下:

def func(s):
    for i in range(len(s)):
        if s.count(s[i]) == 1:
            return i
    return -1

0
投票

Counter很好地解决了这个问题:

from collections import Counter

def f(s):
     return min([s.index(k) for k,v in Counter(s).items() if v == 1], default=-1)
© www.soinside.com 2019 - 2024. All rights reserved.