我们想在给定的字符串 s 中找到乘以无限次的 'a' 的数量。
我们将得到一个数字 n,它是无限字符串的切片大小。
样本输入
阿坝
10
输出:- 7
这里 aba 乘以 10 得到“abaabaabaa”
并且'a'的数量是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
我得到 2 而不是 7 作为输出(测试用例 'aba' 10)。我哪里做错了?我只是将给定的字符串与 n 相乘,因为它永远不会大于切片大小。
这是问题的链接
https://www.hackerrank.com/challenges/repeated-string/problem
最佳答案
使用python3的更简单的解决方案。
s = input().strip()
n = int(input())
print(s[:n%len(s)].count('a')+(s.count('a')*(n//len(s))))
关于python - 使用python在hackerrank中重复字符串问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62024943/