CodeWars 코딩 문제 2021/01/12 - Consecutive Count

이호현·2021년 1월 12일
0

Algorithm

목록 보기
48/138

[문제]

I want to know the longest length of consecutive items of X there are in Y. I will provide you an item (Y), and a key to search for (X). Return the length of the longest segment of consecutive keys (X) in Y.

Rules:
The item will be either an integer or string data type.
The key will be an integer or string data type.
The return value will be an integer data type.
If the key does not appear in the number, return 0.

Example1:
items = 90000;
key = 0;
return value: 4;

Example2:
items = 'abcdaaadse';
key = 'a';
return value: 3;

(요약) key값이 items에서 가장 길게 연속되는 길이를 구하라.

[풀이]

function getConsectiveItems(items, key){
  let answer = 0;
  items = typeof items === 'string' ? items : `${items}`;
  key = typeof key === 'string' ? key : `${key}`;
  const length = items.length;

  for(let i = 0; i < length; i++) {
    if(items[i] === key) {
      let count = 1;

      for(let j = i + 1; j < length; j++) {
        if(items[j] !== key) break;
   
        count++;
      }
  
      answer = answer < count ? count : answer;
    }
  }

  return answer;
}

items에서 key가 시작 되는 위치를 찾고, 거기서부터 몇 번 연속되는지 카운팅해서 return.

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

0개의 댓글