[Lv.0] 문자열이 몇 번 등장하는지 세기

woodstock·2024년 2월 28일
0

코딩테스트

목록 보기
52/56
post-thumbnail

문자열이 몇 번 등장하는지 세기

문제설명

문자열 myStringpat이 주어집니다. myString에서 pat이 등장하는 횟수를 return 하는 solution 함수를 완성해 주세요.

풀이

function solution(myString, pat) {
  let count = 0;
  let startIndex = 0;
  
  while (true) {
    startIndex = myString.indexOf(pat, startIndex);
    if (startIndex === -1) break;
    count++;
    startIndex++;
  }
  return count;
}

풀이해설

const myString = "banana";
const pat = "ana";

첫 번째 반복
startIndex = myString.indexOf(pat, startIndex);
  • "banana"에서 "ana"를 startIndex인 0번 인덱스부터 찾는다.
  • "ana"는 1번 인덱스에서 발견된다.
    "b[ana]na"
  • startIndex는 1이 된다.

if (startIndex === -1) break;

count++;
startIndex++;
  • startIndex가 -1이 아니라면 과정을 다시 반복한다.
    • startIndex === -1 : 해당하는 인덱스를 찾지 못했다.
    • startIndex !== -1 : 해당하는 인덱스를 찾았다.
  • count는 1이 된다.
  • startIndex는 2가 된다.

두 번째 반복
startIndex = myString.indexOf(pat, startIndex);
  • 이제 "banana"에서 "ana"를 startIndex인 2번 인덱스부터 다시 찾는다.
  • "ana"는 3번 인덱스에서 다시 발견된다.
    "ban[ana]"

if (startIndex === -1) break;

count++;
startIndex++;
  • startIndex가 -1이 아니기 때문에 과정을 다시 반복한다.
  • count는 2가 된다.
  • startIndex는 4가 된다.

세 번째 반복
startIndex = myString.indexOf(pat, startIndex);
  • 이번에는 "banana"에서 "ana"를 startIndex인 4번 인덱스부터 찾는다.
  • 이 위치에서는 "ana"가 더 이상 발견되지 않아 indexOf는 -1을 반환한다.

if (startIndex === -1) break;
  • startIndex가 -1이 되었으므로 반복문은 종료된다.

return count;
  • count의 현재 값인 2가 반환된다.

따라서, 결과는 다음과 같다.

solution("banana", "ana"); // 2
profile
해내는 사람

0개의 댓글