본문 바로가기
프로그래밍/알고리즘, 프로그래밍 언어

[코딩테스트] identical characters (JavaScript)

by 제이콥J 2022. 2. 3.

문제

설명

Implement a function that, given a string, Finds the longest run of identical characters and returns an array containing the start and end indices of that run. If there are two runs of equal length, return the first one.

매개변수

str : 문자열 (1 <= str <= 10,000)

아웃풋

[start index, end index] 형태의 배열

 

 

Solution1

for 문으로 str을 순회하며, 최대 길이의 문자열을 찾기

indexOf 메소드로 최대 길이 문자열의 시작 인덱스 구하기

 

function test2(str) {

  // 엣지케이스 처리
  if (str.length ===0) return null;

  let maxStr = ''  // 최대 길이 문자열을 담을 변수 maxStr 선언
  let iden = ''    // identical character를 담을 변수 선언

  for (let i=0; i<str.length; i++) {
    if (str[i]===str[i+1]) {
      iden = iden + str[i];
    } else {
      if (iden.length !== 0) {
        iden = iden + str[i];
        if (maxStr.length < iden.length) maxStr = iden;
        iden = ''
      }
    }
  }

  let idx = str.indexOf(maxStr);
  
  if (maxStr.length ===0) return [0,0]
  
  return [idx, idx + maxStr.length - 1]
  
};

 

 

Solution2

반복문을 순회하며 최대길이 문자열의 시작 인덱스와 마지막 인덱스를 바로 구하기

 

function test(str) {

  // 엣지 케이스 처리
  if (!str) {
    return null;
  }

  let currentCount = 1;  // 현재 문자열의 길이
  let topCount = 0;      // 최대 길이 문자열의 길이
  let currentStart = 0;  // 현재 문자열의 시작 인덱스
  let topStart = 0;      // 최대 길이 문자열의 시작 인덱스
  let topEnd = 0;        // 최대 길이 문자열의 마지막 인덱스

  for (let i = 1; i < str.length; i++) {
    if (str[i] === str[i - 1]) {
      currentCount++;
      if (currentCount > topCount) {
        topCount = currentCount;
        topStart = currentStart;
        topEnd = i;
      }
    } else {
      currentCount = 1;
      currentStart = i;
    }
  }

  return [topStart, topEnd];
};

 

반응형

댓글