HackerRank Java Repeated String


Lilah has a string, , of lowercase English letters that she repeated infinitely many times.
Given an integer, , find and print the number of letter a's in the first  letters of Lilah's infinite string.
For example, if the string  and , the substring we consider is , the first  characters of her infinite string. There are  occurrences of a in the substring. 
Function Description
Complete the repeatedString function in the editor below. It should return an integer representing the number of occurrences of a in the prefix of length  in the infinitely repeating string. 
repeatedString has the following parameter(s): 
  • s: a string to repeat 
  • n: the number of characters to consider 
Input Format
The first line contains a single string, . 
The second line contains an integer, .
Constraints
  • For  of the test cases, .
Output Format
Print a single integer denoting the number of letter a's in the first  letters of the infinite string created by repeating  infinitely many times.
Sample Input 0
aba
10
Sample Output 0
7
Explanation 0 
The first  letters of the infinite string are abaabaabaa. Because there are  a's, we print  on a new line.
Sample Input 1
a
1000000000000
Sample Output 1
1000000000000
Explanation 1 
Because all of the first  letters of the infinite string are a, we print  on a new line.


문제 요약 : 
첫 번째 라인에 반복할 문자열이 주어지고, 
두 번째 라인에 문자열로 반복해서 만들 문자열의 길이가 주어진다.
반복해서 만든 문자열에서 a의 횟수를 리턴해주는 함수를 작성하면 된다.

ex) 
첫 번째  라인 : abcda
두 번째 라인 : 50
abcdaabcdaabcdaabcdaabcdaabcdaabcdaabcdaabcdaabcda
a의 횟수 = 20

접근 방법 : 무식하게 문자열을 두 번째 입력만큼 붙여서 만든 다음 반복문으로 a의 개수를 세는 방법도 있을것이다.
하지만 이방법은 문자열이 길어질수록 그리고 반복하는 횟수가 커질수록 시간이 굉장히 늘어난다.

따라서 아래와 같이 풀어보았다.

우선 문자열에서 a의 횟수를 구한다. 위의 예시는 2번 나온다.
그리고 문자열의 길이로 반복하는 횟수에서 몫과 나머지를 구한다.
위의 예시에서는  몫은 10이고 나머지는 0이다.

문자열에서 (a의 횟수 * 몫) + ( 나머지만큼 문자열에서 a의 출연횟수를 더해준다)
위의 예시에서는 (2 * 10) + 0 = 20
따라서 20이 된다.

만약에 아래와 같이 주어진다면,
abcda
52
a의 횟수는 = 21이 된다.
abcdaabcdaabcdaabcdaabcdaabcdaabcdaabcdaabcdaabcdaab가 된다.
(2 * 10 ) + 1 = 21




댓글

이 블로그의 인기 게시물

About JVM Warm up

About idempotent

About Kafka Basic

About ZGC

sneak peek jitpack

Spring Boot Actuator readiness, liveness probes on k8s

About Websocket minimize data size and data transfer cost on cloud

About G1 GC

대학생 코딩 과제 대행 java, python, oracle 네 번째