wilkins

老实做人

导航

找到第一个不重复的字符

问题描述:在字符串中找到第一个不重复的字符,如,'total'中第一个不重复的字符为'o'。

思想:扫描两次字符串,第一次:建立一个对应字符的字典,键值为“出现一次”和“不是一次”;第二次:扫描出第一个键值为“出现一次的”字符。

def searchOnce(s):
    if len(s)==0:
        return -1
    elif len(s)==1:
        return s[0]
    else:
        sDic={}
        once=1
        notonce=2
        for word in s:
            if not sDic.get(word):
                sDic[word]=once
            else:
                sDic[word]=notonce
        for word in s:
            if sDic[word]==once:
                return word
        return -1

if __name__ == "__main__":
    s='teeth'
    print searchOnce(s)

扫描两次,时间复杂度为O(n)。建立字典,空间复杂度增加,最坏为n。

 

posted on 2015-04-07 13:50  wilkins  阅读(169)  评论(0编辑  收藏  举报