【问题标题】:Find the Letters Occurring Odd Number of Times找出出现奇数次的字母
【发布时间】:2020-02-02 14:59:44
【问题描述】:

我遇到了一个有趣的问题,我想知道我们是否可以解决它。

背景

在时间复杂度O(n)中,能否找到出现奇数次的字母,输出一个包含字母的列表,保持字母顺序与原字符串一致.

如果有多个选项可供选择,则将最后出现的字符作为未配对字符。

这是一个例子:

# note we should keep the order of letters
findodd('Hello World')   ==  ["H", "e", " ", "W", "r", "l", "d"] # it is good
findodd('Hello World')   ==  ["H", "l", " ", "W", "r", "e", "d"] # it is wrong

我的尝试

def findodd(s):
    hash_map = {}

    # This step is a bit strange. I will show an example:
    # If I have a string 'abc', I will convert string to list = ['a','b','c']. 
    # Just because we can not use dict.get(a) to lookup dict. However, dict.get('a') works well.
    s = list(s)

    res = []
    for i in range(len(s)):
        if hash_map.get(s[i]) == 1:
            hash_map[s[i]] = 0
            res.remove(s[i])
        else:
            hash_map[s[i]] = 1
            res.append(s[i])

    return res
findodd('Hello World')

输出:

["H", "e", " ", "W", "r", "l", "d"] 

但是,由于我使用list.remove,因此在我的解决方案中时间复杂度高于 O(n)。

我的问题:

  1. 谁能提供一些关于O(n)解决方案的建议?
  2. 如果我不想使用s = list(s),如何遍历字符串'abc' 以在字典中查找key = 'a' 的值? dict.get('a') 有效,但 dict.get(a) 无效。

来源

这是我看过的 2 个网页,但是他们没有考虑字母顺序,也没有提供 O(n) 解决方案。

  1. find even time number, stack overflow
  2. find odd time number, geeks for geeks

【问题讨论】:

  • 你给出的例子,我认为“l”应该在字母“e”之后而不是在“r”之后。
  • @schlodinger 再添加一句话来澄清。在“Hello World”的情况下,我们应该把l放在它最后一次出现的地方。

标签: python algorithm dictionary lookup


【解决方案1】:

Python 3.7 以上的字典键输入是有序的。使用collection.OrderedDict 用于较低的python 版本。

检查你的单词,如果不在,则添加字母 do dict,否则从 dict 中删除键。

解决方案是 dict.keys() 集合:

t = "Hello World"

d = {}
for c in t:
    if c in d:       # even time occurences: delete key
        del d[c]
    else:
        d[c] = None  # odd time occurence: add key

print(d.keys()) 

输出:

dict_keys(['H', 'e', ' ', 'W', 'r', 'l', 'd'])

它的 O(n) 因为您只触摸输入中的每个字母一次 - 查找 dict 是 O(1)。

添加/删除键会产生一些开销。如果这让您感到困扰,请改用计数器并为奇数的那些过滤 key() 集合 - 这将使其 O(2*n) - 2 是恒定的,所以仍然是 O(n)。

【讨论】:

    【解决方案2】:

    这是一个尝试(键在 python 3.6 dict 中排序):

    from collections import defaultdict
    
    def find_odd(s):
        counter = defaultdict(int)
        for x in s:
            counter[x] += 1
        return [l for l, c in counter.items() if c%2 != 0]
    

    这个算法的复杂度小于2n,也就是O(n)!

    示例

    >>> s = "hello world"
    >>> find_odd(s)
    ['h', 'e', 'l', ' ', 'w', 'r', 'd']
    

    【讨论】:

      【解决方案3】:

      您可以使用哈希映射来存储字符出现的索引,并在它已经有值时切换它。

      然后您只需再次迭代字符串并仅保留那些出现在您在哈希映射中的索引处的字母:

      from collections import defaultdict
      
      def findodd(s):
          hash_map = defaultdict(int)
          for i, c in enumerate(s):
              hash_map[c] = 0 if hash_map[c] else i+1
          return [c for i, c in enumerate(s) if hash_map[c] == i+1]
      

      【讨论】:

        【解决方案4】:

        我从头开始的解决方案

        它实际上使用了Python 3.6中的dict是按键排序的特性。

        def odd_one_out(s):
        
            hash_map = {}
            # reverse the original string to capture the last occurance
            s = list(reversed(s))
            res = []
            for i in range(len(s)):
                if hash_map.get(s[i]):
                    hash_map[s[i]] += 1
        
                else:
                    hash_map[s[i]] = 1
            for k,v in hash_map.items():
                if v % 2 != 0:
                    res.append(k)
        
            return res[::-1]
        

        疯狂的超短解

        #from user FArekkusu on Codewars
        from collections import Counter
        
        def find_odd(s):
            d = Counter(reversed(s))
            return [x for x in d if d[x] % 2][::-1]
        

        【讨论】:

          【解决方案5】:

          使用集合中的计数器将为您提供 O(n) 解决方案。由于 Counter 对象是一个字典(保持出现顺序),因此您的结果可以简单地是计数的过滤器:

          from collections import Counter
          
          text = 'Hello World'
          oddLetters = [ char for char,count in Counter(text).items() if count&1 ]
          print(oddLetters) # ['H', 'e', 'l', ' ', 'W', 'r', 'd']
          

          【讨论】:

            猜你喜欢
            • 2015-02-06
            • 1970-01-01
            • 1970-01-01
            • 2017-09-13
            • 2023-03-19
            • 1970-01-01
            • 2013-09-08
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多