CodeWars 코딩 문제 2021/04/21 - Adjacent repeated words in a string

이호현·2021년 4월 21일
0

Algorithm

목록 보기
107/138

[문제]

You know how sometimes you write the the same word twice in a sentence, but then don't notice that it happened? For example, you've been distracted for a second. Did you notice that "the" is doubled in the first sentence of this description?

As as aS you can see, it's not easy to spot those errors, especially if words differ in case, like "as" at the beginning of this sentence.

Write a function that counts the number of sections repeating the same word (case insensitive). The occurence of two or more equal words next after each other counts as one.

Examples
"dog cat" --> 0
"dog DOG cat" --> 1
"apple dog cat" --> 0
"pineapple apple dog cat" --> 0
"apple apple dog cat" --> 1
"apple dog apple dog cat" --> 0
"dog dog DOG dog dog dog" --> 1
"dog dog dog dog cat cat" --> 2
"cat cat dog dog cat cat" --> 3

(요약) 다른 문자열이 나오기 전까지 자신과 같은 (대소문자 구분 X) 문자열이 반복되는 구간이 몇 번인지 구하라.

[풀이]

function countAdjacentPairs(searchString) {
  let answer = 0;
  const splitArr = searchString.split(' ');
  let tempStr = splitArr[0].toLowerCase();
  let check = false;

  for(let i = 1; i < splitArr.length; i++) {
    const currentStr = splitArr[i].toLowerCase();

    if(tempStr === currentStr) {
      check || (answer += 1);
      check = true;
    }
    else {
      tempStr = currentStr;
      check = false;
    }
  }

  return answer;
}

반복되는 문자열 임시 보관할 tempStr, 반복 되는지 확인할 check변수를 만듦.

첫 문자열을 tempStr에 넣고, 반복문으로 두 번째 문자열부터 확인.

같을 경우 반복되는지 확인이 됐다면 checkfalse일 때만 answer증가시키고, checktrue로 바꿈.

다른 문자열일 경우 tempStr에 현재 문자열을 넣고, checkfalse로 바꿈.

profile
평생 개발자로 살고싶습니다

0개의 댓글