查找固定长度字符串的所有可能子序列

时间:2021-03-09 19:57:01

标签: arrays string list algorithm

我昨天从 CodinGame 得到了这个问题。

注意:我不知道如何解释这个注释,所以我将通过示例来解释它: 字符串“hey”具有以下长度为 2 的子序列:“he”、“hy”和“ey”。

我的尝试:我有一个解决方案的想法,但实际实施起来有点复杂。 这个想法是:我们制作一个包含所需子序列长度的列表。我们尝试在上述限制下遍历所有可能的列表。用下一个元素循环遍历所有可能的元素是不够的,因为会丢失可能的列表。

我觉得我自己已经试够了,是时候问问stackoverflow了。

3 个答案:

答案 0 :(得分:1)

子序列(长度为 k)要么包含第一个字母,要么不包含。在第一种情况下,您需要来自字符串其余部分的所有长度为 k-1 的子序列。在第二种情况下,您需要长度为 k 的所有子序列,同样来自字符串的其余部分。这种观察导致了一个简单的递归。在伪代码中,

list_subsequences(s, k)
    if len(s) < k or k == 0
        return empty set
    c = first character of s
    s1 = tail of s (first character removed)
    set1 = list_subsequences(s1, k-1)
    prepend c to all strings in s1
    set2 = list_subsequences(s1, k)
    return set1 + set2

答案 1 :(得分:1)

这是 Python 中的一个实现示例,使用递归函数。

def subsequence(text, subseq_length):
  if subseq_length <= 0:
    return []

  if subseq_length == 1:
    return list(text)

  text_length = len(text)
  res = []
  tail_length = subseq_length - 1
  for i in range(0, text_length - tail_length):
    for tail in subsequence(text[i+1:], tail_length):
      res.append(text[i] + tail)
  return res

print(subsequence('hey', 2))
print(subsequence('hello', 3))

输出:

['he', 'hy', 'ey']
['hel', 'hel', 'heo', 'hll', 'hlo', 'hlo', 'ell', 'elo', 'elo', 'llo']

答案 2 :(得分:0)

您可以使用itertools.combinations

import itertools

x = list(set(list(itertools.combinations(["h","e","y"] , 2) ) ) )
x = [ "".join(i) for i in x ]
print(x)

>> ['he', 'ey', 'hy']

另一个使用“hello”的例子

x = list(set(list(itertools.combinations(["h","e","l","l","o"] , 2) ) ) )
x = [ "".join(i) for i in x ]
print(x)

>> ['ho', 'lo', 'el', 'eo', 'he', 'll', 'hl']


x = list(set(list(itertools.combinations(["h","e","l","l","o"] , 3) ) ) )
x = [ "".join(i) for i in x ]
print(x)


>> ['heo', 'hlo', 'elo', 'ell', 'hll', 'llo', 'hel']