본문 바로가기
Algorithm/문제풀이

[HackerRank] Repeated String (Easy) by javascript

by 썸머워즈 2022. 4. 19.
반응형

▷ 문제 : Repeated String (Easy)

 

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

▷ 해결 날짜 : 2022.04.19
▷ 소요 시간 : 20분
▷ 풀이 과정 :
문자열과 최대길이가 주어지고

문자열을 최대길이까지 반복했을때 나오는 'a'문자가 몇개인지 반환하는 문제이다.

 

제한사항에 주어진 문자열의 길이제한이 너무 길어서 그냥 단순하게 풀면 에러가 발생한다.

그래서 우선 최대한 문자열의 원본상태가 반복되는 구간까지 구한다음 나머지 문자열을 잘라 붙이고

거기서 각각의 'a'문자의 길이를 뽑아내 결과로 반환하였다.


▷ 구현

function repeatedString(s, n) {
    // Write your code here
    let ln = s.length;
    let repeat = Math.floor(n / ln);
    return (s.replace(/[^a]/g, '').length * repeat) + s.slice(0, (n % ln)).replace(/[^a]/g, '').length;
}


▷ 복기 :
나름 재밌었다.

반응형


댓글

TOP