【问题标题】:How to find how many sub strings can be formed from a given string?如何从给定的字符串中查找可以形成多少个子字符串?
【发布时间】:2020-07-07 19:53:28
【问题描述】:

我被困在我有两个字符串的情况:

#EXAMPLE 1:
S = "appleapplesre"
Y = "apple"

我想找出字符串 Y 在 S 中出现的次数不重复任何字符(即,这里出现两次)

#EXAMPLE 2:
S = "apqrctklatc"
Y = "cat"

这里字符串 Y 也可以使用字符串 S 出现 2 次。

我已经到了这个编码阶段,但不知道如何从这里开始:

#Write your implementation here
S = "appleapplesre"
Y = "apple"
char_s = ''
char_y = ''

#Character count for given string S
print(S)
for char in S:
    if(char not in char_s):
        count = S.count(char)
        print(char,count)
    char_s += char
   
print()

#Character count for given string Y
print(Y)
for char in Y:
    if(char not in char_y):
        count = Y.count(char)
        print(char,count)
    char_y += char
    
if(char_y in char_s):
    print('True')

***OUTPUT:***
appleapplesre
a 2
p 4
l 2
e 3
s 1
r 1

apple
a 1
p 2
l 1
e 1
True

【问题讨论】:

  • 在您的第二个示例中,您是在寻找str 比较还是char 比较?

标签: python string substring


【解决方案1】:

你想知道Y的字符在S中能找到多少次。

您可以简单地计算两个字符串中的字符数,然后对于Y 中的每个字符,计算其在S 中的出现率与其在Y 中的出现率之比。你的答案是这些比率中最小的一个。

使用collections.Counter,您可以这样做:

from collections import Counter

s = "apqrctklatc"
y = "cat"

s_counts = Counter(s)
y_counts = Counter(y)

repetitions = min(s_counts[char]//y_counts[char] for char in y_counts.keys())

print(repetitions)
# 2

【讨论】:

  • 哈哈该死的答案几乎相同——同时也在研究它
【解决方案2】:

这也起到了作用,建立在与 Thierry Lathuille 相同的逻辑之上:

S = "apqrctklatc"
Y = "cat"

repetitions = min(S.count(char)//Y.count(char) for char in set(Y))
print(repetitions)  # 2

【讨论】:

    【解决方案3】:

    我认为你可以这样做:

    from collections import Counter
    
    def get_num(string, word, num=0):
        counts = Counter(string)
        word_counts = Counter(word)
        while True:
            for key, val in word_counts.items():
                counts[key] -= val
            if any([val < 0 for val in counts.values()]):
                break
            else:
                num += 1
        return num
    
    print(get_num("appleapplesre", "apple")) #2
    print(get_num("apqrctklatc", "cat")) #2
    

    这会计算您有多少个可用字母,并减去每次取出所需单词时需要多少个,当计数低于 0 时,表示没有足够并结束循环

    【讨论】:

      猜你喜欢
      • 2023-01-19
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-13
      • 2021-11-08
      • 2016-04-20
      相关资源
      最近更新 更多