繁体   English   中英

查找某个字符在相乘字符串中出现的次数

[英]Finding how many times a certain character appears in a multiplied string

我们想找到给定字符串s中的 'a' 的数量无限次相乘。 我们将得到一个数字n ,它是无限字符串的切片大小。

样本输入:
aba 10

output:
7

这里aba乘以 10,得到 'abaabaabaa' 和 no。 '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

我得到 2 而不是 7 作为 output (测试用例 'aba' 10)。 我在哪里 go 错了? 我只是将给定的字符串与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))))

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

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

如果您想要一个更具可读性的答案......

def repeatedString(s, n):
    target = 'a'
    target_count = 0

    # how many times does the string need to be repeated: (n // len(s) * s) + s[:(n % len(s))] 
    quotient = n // len(s)
    remainder = n % len(s)

    for char in s:  # how many times target appears in 1 instance of the substring
        if char == target:
            target_count += 1
        
    # how many times the target appears in many instances of the substring provided
    target_count = target_count * quotient

    for char in s[:remainder]:  # count the remaining targets in the truncated substring
        if char == target:
            target_count += 1

    return target_count

因此,如果字符串包含“a”,则只需简单地返回 n。 否则,计算字符串 s 中 a 的数量,现在使用 divmond() function 我找到了可以添加的字符串数量不超过 n。 例如字符串 s 是“aba”并且 n=10,所以我可以完全添加 3 个“abs”,而字符串的长度不会超过 10。现在添加的字符串中的 a 的数量(3 * 2)。 现在剩下要填充的位置等于 divmond() function 的余数(y)。 现在将字符串 s 切成 y 并找到其中 a 的数量并将其添加到计数中。

divmond(10,3) 返回 (10//3) 并且是余数。

def repeatedString(s, n):
    if len(s)==1 and s=="a":
        return n
    count=s.count("a") 
    x,y=divmod(n,len(s))
    count=count*x
    str=s[:y]
    return count+str.count("a")

Python 3中的解决方案:

def repeatedString(s,n):
    i = 0
    c = 0
    for i in s:
        if i == 'a':
            c += 1

    q = int(n / len(s)) #Finding the quotient 
    r = int(n % len(s)) #Finding the remainder
    if r == 0: 
        c *= q 

    else:
        x = 0
        for i in range(r):
            if s[i] == 'a':
                x += 1
        c = c*q + x

    return int(c)

s = input()
n = int(input())
print(repeatedString(s,n))

我使用了一个简单的单一方法。 一次重复中的“a”数为cnt_a ,因此前n字符中的“a”数将为(cnt_a/len(s)) * n

def repeatedString(s, n):
    if len(s)==1 and s=='a':
        return n
    cnt_a=0
    for i in s:
        if i == 'a':
            cnt_a+=1
    if cnt_a % 2 == 0:
        no_a = (cnt_a/len(s)) * n
        return math.ceil(no_a)
    else:
        no_a = (cnt_a/len(s)) * n
        return math.floor(no_a)
如果字符'a'出现在给定的字符串模式中,那么获得它的重复计数会更快,然后根据提到的最终字符串的总长度,将尝试重复给定模式相同的次数&因此将重复计数与字符串模式将重复的次数相乘。 重要的是,如果最终的字符串输入是奇数,那么我们需要识别那些奇数模式并单独计算奇数字符串模式中字符“a”的出现次数。 最后总结总计数(偶数和奇数)会给我们预期的结果
def repeatedString(s, n): # Get the length of input string strlen = len(s) a_repeat = 0 # Get the total count of a repeated character from the input string for i in range(0,strlen): if s[i] == 'a': a_repeat = a_repeat + 1 # Get the multiplier to make sure that desired input string length achieved str_multiplier = int(n // strlen) # Get the repeated count if new string is been created result = a_repeat*str_multiplier new_str = s[:int( n % strlen )] # for odd length of string, get the remaining characters and find repated characters count and add up it to final count for i in range(0, len(new_str)): if new_str[i] == 'a': result += 1 return result

一个班轮回答:

return [s[i%len(s)] for i in range(n)].count('a')

您的代码中只有两个问题

s = 'aba'
n = 10
    
count = 0
inters = s * n

# Here you need to slice(inters) not (s) because s only hold 'aba'
# And not n+1 it's take 11 values only n
reals = inters[0:n]
  for i in reals:
    if (i == 'a'):
      count += 1
    
print(count)

对于这个问题,获取字符串 s 的长度。 一、if条件:约束

现在,我们不使用循环来增加空间和时间复杂度,而是使用基本数学。 求 n//Len (s) 的商。 现在找到我们的字符串中使用“a”的次数。

我们可以将商乘以这个数字,得到使用的总“a”。 现在,我们可以找到字符串的剩余部分,并使用 slice 在我们最后留下的字符串中搜索“a”。

添加两者以获得我们的答案。

def repeatedString(s, n):

#finding quotient and remainder of division

str1=len(s)
remainder=0
if 1<=str1<=100 and 1<=n<=10**12:
    quotient= n//str1 
    a_s = s.count("a")
    
    if a_s==0:
        return 0
    else:
        remainder=s[:n%str1].count('a')
        return quotient*a_s + remainder

简单的回答:

def repeatedString(s, n):
    
    totalNumber = 0 // setting total of a's to 0

    // using count function to find the total number of a's in the substring
    totalNumber = s.count('a')

    // finding how many number of times the substring fits in "n" and multiplying that by the number of a's we found earlier
    totalNumber = n//len(s) * totalNumber 

    // if there is a remainder, we loop through the remainder string and add the number of "a's" found in that substring to the total
    for i in s[:n%len(s)]:
        if(i == "a"):
            totalNumber +=1
        
    return totalNumber

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM