【问题标题】:Given a lowercase string, 's', return the index of the first character that appears just once in the string给定一个小写字符串's',返回字符串中仅出现一次的第一个字符的索引
【发布时间】:2019-11-30 19:17:21
【问题描述】:

""" 如果每个字符出现多次,则返回 -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


【解决方案1】:

试试这个:

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

【讨论】:

    【解决方案2】:

    我认为这是一种简单的方法:

    def f(s):
        for i,c in enumerate(s):
            if s.count(c) == 1:
                return i
        return -1
    
    assert f("who wants hot watermelon?") ==  8
    assert f("aa") == -1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-02
      • 2013-05-07
      • 2010-12-12
      • 2022-12-04
      • 2017-02-22
      • 2022-12-01
      相关资源
      最近更新 更多