在完成【剑指offer】试题 第一个只出现一次的字符位置 时,写了如下代码:

class Solution:
    def FirstNotRepeatingChar(self, s):
        # write code here
        m = {}
        for i in range(0, len(s)):
            if len(m.keys()) == 0:
                m[s[i]] = i
            else:
                if s[i] in m.keys():
                    m[s[i]] = -1
                else:
                    m[s[i]] = i

        for key in m.keys():
            if m[key] != -1:
                return m[key]
        return -1

在牛客网的编程环境中运行一直报错,多次检查没有错误后,我把上述代码放到PyCharm中运行(即下列代码),发觉没有报错:

# -*- coding:utf-8 -*-

def FirstNotRepeatingChar(s):
    # write code here
    m = {}
    for i in range(len(s)):
        if len(m) == 0:
            m[s[i]] = i
        else:
            if s[i] in m.keys():
                m[s[i]] = -1
            else:
                m[s[i]] = i

    for key in m.keys():
        if m[key] != -1:
            print(key)
            return m[key]
    return -1

print(FirstNotRepeatingChar('NXWtnzyoHoBhUJaPauJaAitLWNMlkKwDYbbigdMMaYfkVPhGZcrEwp'))

查询资料后知道:python 2.7中字典z是无序的,python3.6之后字典次才变成有序。

改进的python 2.7代码如下所示:

# -*- coding:utf-8 -*-
'''
学到的知识点,python2.7版本的字典是无序的,python3.x是有序的
'''
class Solution:
    def FirstNotRepeatingChar(self, s):
        # write code here
        keys = []
        m = {}
        for i in range(0, len(s)):
            if len(m.keys()) == 0:
                keys.append(s[i])
                m[s[i]] = i
            else:
                if s[i] in m.keys():
                    m[s[i]] = -1
                else:
                    keys.append(s[i])
                    m[s[i]] = i

        for key in keys:
            if m[key] != -1:
                return m[key]
        return -1