使用python在hackerrank中重复字符串问题?

Muh*_*med 4 python string python-3.x

我们想在给定的字符串 s 中找到乘以无限次的 'a' 的数量。我们将得到一个数字 n,它是无限字符串的切片大小。样本输入 aba 10

输出:- 7 此处 aba 乘以 10 产生 'abaabaabaa' 并且 'a's 的数量是 7 这是我的代码

def repeatedString(s, n):
    count = 0
    inters = s * n
    reals = s[0:n+1]
    for i in reals:
        if (i == 'a'):
            count += 1
    return count
Run Code Online (Sandbox Code Playgroud)

我得到 2 而不是 7 作为输出(测试用例 'aba' 10)。我哪里做错了?我只是将给定的字符串与 n 相乘,因为它永远不会大于切片大小。

这是问题的链接 https://www.hackerrank.com/challenges/repeated-string/problem

voi*_*pro 6

使用python3的更简单的解决方案。

s = input().strip()
n = int(input())
print(s[:n%len(s)].count('a')+(s.count('a')*(n//len(s))))
Run Code Online (Sandbox Code Playgroud)

  • 由于该人提到他正在使用黑客级别,因此在解决此问题时最好坚持使用他自己的算法。 (2认同)

A. *_*mov 2

没有理由对字符串进行切片

def repeatedString(s, n):
    count = 0
    for index, i in enumerate(s*n):
        if index >= n:
            return count
        if(i == 'a'):
            count += 1
    # empty string
    return count
Run Code Online (Sandbox Code Playgroud)