python【练习】输入一个字符串,找到它的第一个不重复的字符并把它的索引输出出来,否则返回-1

#方法一:
def test_string_unique(arr):
    dic = {}
    if not arr:
        return -1
    for index in range(len(arr)):
        if arr[index] in dic:
            dic[arr[index]] += 1
        else:
            dic[arr[index]] = 1
    
    for j in dic:
        if dic[j] == 1:
            result = arr.index(j)
            break
    return result


string = "abcab"
print(test_string_unique(string))

#方法二:
from collections import Counter

def deal_str(s):
    counter = Counter(s)
    singles = [_c for _c, _i in counter.items() if _i == 1]
    idxs = [s.index(_c) for _c in singles]
    idx = min(idxs) if idxs else -1
    print(f"字符串({s})中的第一个不重复字符的位置是({idx})")



#方法三:
def deal_str2(s):
    my_dict = {}
    idx = -1
    for _i, _c in enumerate(s):
        if _c not in my_dict:
            my_dict[_c] = _i
        else:
            my_dict[_c] = 9999
    idx = min(my_dict.values())
    idx = -1 if idx >= 9999 else idx
    print(f"字符串({s})中的第一个不重复字符的位置是({idx})")

输出:

python【练习】输入一个字符串,找到它的第一个不重复的字符并把它的索引输出出来,否则返回-1_第1张图片

 

你可能感兴趣的:(练习题,python)