【发布时间】: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)。
我的问题:
- 谁能提供一些关于O(n)解决方案的建议?
- 如果我不想使用
s = list(s),如何遍历字符串'abc'以在字典中查找key = 'a'的值?dict.get('a')有效,但dict.get(a)无效。
来源
这是我看过的 2 个网页,但是他们没有考虑字母顺序,也没有提供 O(n) 解决方案。
【问题讨论】:
-
你给出的例子,我认为“l”应该在字母“e”之后而不是在“r”之后。
-
@schlodinger 再添加一句话来澄清。在“Hello World”的情况下,我们应该把
l放在它最后一次出现的地方。
标签: python algorithm dictionary lookup