알고리즘/HackerRank

Repeated String

webmaster 2021. 11. 18. 19:14
728x90

https://www.hackerrank.com/challenges/repeated-string/problem?isFullScreen=true&h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup 

 

Repeated String | HackerRank

Find and print the number of letter a's in the first n letters of an infinitely large periodic string.

www.hackerrank.com

 

  • 문제
    • 문제
    • n길이까지 반복되는 s 중 a가 몇 번 나오는 지를 출력

풀이

  • 문자열을 돌면서 a가 몇번 나오는지 count  
  • (n-1)을 문자열 길이로 나눈 값 만큼 a가 나온 횟수를 곱해준다
  • (n-1)을 문자열 길이로 나눈 나머지 값만큼 for문을 다시 돌아 a가 몇 번 나오는지 계산해 count
  • 결과를 리턴한다
  •   public static long repeatedString(String s, long n) {
        int fre = 0; // 문자열 내 a 횟수
        for(char c : s.toCharArray()) {
        	if(c == 'a') {
        		fre++;
        	}
        }
        long count = fre * ((n-1) / s.length()); // 문자열 내 a 횟수 * ((n-1) / 문자열 길이) 
        int idx = (int) ((n-1) % s.length()); // 문자열 어디까지 돌았는지 
        for(int i=0;i <=idx;++i) {//중간에 끊긴 지점 까지 for문
        	char c = s.charAt(i);
        	if(c == 'a')
        		count++;
        }
        return count;
      }
 
728x90

'알고리즘 > HackerRank' 카테고리의 다른 글

Arrays Left Rotation  (0) 2021.11.18
2D Array - DS  (0) 2021.11.18
Jumping on the Clouds  (0) 2021.11.18
Counting Valleys  (0) 2021.11.18
Sales by Match  (0) 2021.11.18