관리 메뉴

기억을 위한 기록들

[HackerRank/C++] Repeated String 본문

Coding Test - cpp/String

[HackerRank/C++] Repeated String

에드윈H 2021. 7. 25. 19:56

https://www.hackerrank.com/challenges/repeated-string/problem

 

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

 

 

long repeatedString( string s, long n ) {
	long cnt = 0;
	//반복최대 길이보다 문자열이 더 길때
	if( n < s.size() )
	{
		//반복 최대 길이(n)만큼까지에서 a 글자 찾기
		for( long i = 0; i < n; i++ )
		{
			if( s[i] == 'a' )
			{
				cnt++;
			}
		}
		return cnt;
	}
	else
	{
		long aCnt = 0;
		long repeatCnt = n / s.size(); //문자열s의 n길이만큼 총 반복수
		long remainCnt = n % s.size(); // 반복되고 나머지 수 

		//문자열 s에서 a가 몇번 나오는지 세기
		for( long i = 0; i < s.size(); i++ )
		{
			if( s[i] == 'a' )
			{
				aCnt++;

				//ex)s = aba / n= 10
				// abaabaaba   ->repeatCnt는 aba가 3번 반복되어 3
				// abaabaaba a ->remainCnt는 3번반복되고 남은 문자 수 1
				if( i < remainCnt ) //remainCnt 중에서 a가 몇번인지 
				{
					cnt++;
				}
			}

		}
		//총 반복수(repeatCnt)에서 a가 몇번만큼 나오는지
		cnt += aCnt * repeatCnt;
	}
	return cnt;

}