1つの文字列の最初の文字とその位置を取得します.

3276 ワード

分析:
                        ,         1      ,      

仮定文字列:
'stringisastaringb'

解法1:
def first_not_repeating_char(string):
    if not string:
        return -1
    resultDict = {}
    for k, s in enumerate(string):
        resultDict [s] = [resultDict [s][0] + 1,k] if resultDict .get(s) else [1,k]
    pos = len(string)
    ret = None
    for x in resultDict :
        if resultDict [x][0] ==1 and resultDict [x][1] 1]
            ret = (x,pos)
    return ret

データ構造は次の例で構成されています.
    :{'a': [2, 9], 'b': [1, 16], 'g': [2, 15], 'i': [3, 13], 'n': [2, 14], 's': [3, 10], 'r': [2, 12], 't': [2, 11]}

    :('b', 16)

解法2:
           ,     ;
def first_not_repeating_char(string):
    if not string:
        return -1
    count = {}
    loc = {}
    for k, s in enumerate(string):
        count[s] = count[s] + 1 if count.get(s) else 1
        loc[s] = loc[s] if loc.get(s) else k
    pos = len(string)
    ret = None
    for k in loc.keys():
        if count.get(k) == 1 and loc[k] < pos:
            pos = loc[k]
            ret = (k,loc[k])
    return ret

データ構造は次の例で構成されています.
count {'a': 2, 'b': 1, 'g': 2, 'i': 3, 'n': 2, 's': 3, 'r': 2, 't': 2}

loc {'a': 8, 'b': 16, 'g': 5, 'i': 3, 'n': 4, 's': 7, 'r': 2, 't': 1}

('b', 16)