Computer Science/Coding Test

[HackerRank]Repeated String

Nomad Lee 2025. 4. 19. 23:07

[문제 ]

There is a string, s, of lowercase English letters that is repeated infinitely many times. Given an integer, n, find and print the number of letter a's in the first  letters of the infinite string.

문자열 s가 있고, 소문자 영문으로 여러 번 무한으로 반복된다. 주어진 정수 n이 있고, 무한의 문자열에서 첫 글자에 있는 'a'의 개수를 구해 출력하시오.

Example
s = 'abcac'

n = 10

The substring we consider is abcacabcac, the first 10 characters of the infinite string. There are 4 occurrences of a in the substring.

우리가 고려하는 부분 문자열은 무한 문자열의 처음 10개 문자인 abcacabcac입니다. 이 부분 문자열에는 a가 4번 나타납니다.

Function Description

Complete the repeatedString function in the editor below.

repeatedString has the following parameter(s):

  • s: a string to repeat
  • n: the number of characters to consider

repeatedString 함수를 완성하시오

  • s: 반복할 문자열
  • n: 문자의 갯수

Returns

  • int: the frequency of a in the substring

부분 문자열에서 반복되는 a의 빈도수

Input Format

The first line contains a single string, .
The second line contains an integer, .

첫 번째 줄은 문자열을 포함하고, 두 번째 줄은 정수이다.

Sample Input

Sample Input 0

aba
10

Sample Output 0

7

Explanation 0
The first n = 10  letters of the infinite string are abaabaabaa. Because there are 7 a's, we return 7.

무한한 문자열의 첫 n = 10abaabaabaa이다. a가 7개 있기 때문에 7을 반환해 준다.

Sample Input 1

a
1000000000000

Sample Output 1

1000000000000

Explanation 1
Because all of the first n = 1000000000000 letters of the infinite string are a, we return 1000000000000.

무한한 문자열의 처음  n = 1000000000000 문자는 모두 a이기 때문에 를 n = 1000000000000 반환.

[python 코드]

def repeatedString(s, n):
    s_len = len(s)
    a_count = s.count('a')
    m = n // s_len
    a_count *= m
    temp = n % s_len
    a_count += s[:temp].count('a')
    return a_count

 

한 줄 코드

def repeatedString(s, n):
    res = s.count("a") * (n // len(s)) + s[:n % len(s)].count("a")
    return res

 



'Computer Science > Coding Test' 카테고리의 다른 글

[HackerRank] The Minion Game  (1) 2025.04.21
[HackerRank] Jumping on the Clouds  (0) 2025.04.16
[HackerRank] Counting Valleys  (0) 2025.04.15
[HackerRank] Sales by Match  (0) 2025.04.15