HackerRank Repeated String

x·2021년 4월 28일
0

problem-solving

목록 보기
4/18

s라는 문자열이 주어지고 s는 무한히 반복되지만 n만큼만 잘랐을 때 그 안에 a라는 문자가 몇 개나 들어있는지 판단해야 한다

단순하게 보면 s를 n이라는 길이가 될 때까지 반복하고 그 안에서 a 문자를 찾으면 된다. 그러나 너무 느릴 것 같다.

  1. n을 s의 길이로 나는 몫 q, 나머지 r을 구한다.
  2. s에 있는 a의 개수 a_in_s를 구한다.
  3. return a_in_s * q + s[:r].count("a")
#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'repeatedString' function below.
#
# The function is expected to return a LONG_INTEGER.
# The function accepts following parameters:
#  1. STRING s
#  2. LONG_INTEGER n
#

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

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    n = int(input().strip())

    result = repeatedString(s, n)

    fptr.write(str(result) + '\n')

    fptr.close()

0개의 댓글