Unique In Order ( 6 kyu )

문제

Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.

For example:

uniqueInOrder('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
uniqueInOrder('ABBCcAD')         == ['A', 'B', 'C', 'c', 'A', 'D']
uniqueInOrder([1,2,2,3,3])       == [1,2,3]

문자열에서 연속으로 중복되는 단어를 제거해 배열로 리턴하는 문제

풀이

var uniqueInOrder=function(iterable){
  if ( !iterable ) return [];
  let temp = iterable[0], result = [];
  for ( let i = 1; i < iterable.length; i++ ) {
    if ( iterable[i] !== temp ) {
      result.push(temp);
      temp = iterable[i];
    }
  }
  result.push(iterable[iterable.length-1])
  return result;
}

가장 윗줄은 빈 배열일 때 예외처리

temp에 문자가 바뀌면 등록해놓고 새로운 문자로 바뀔때마다 result배열에 푸시, 마지막 인덱스 푸시 후 리턴

다른 사람의 풀이

function uniqueInOrder(it) {
  var result = []
  var last

  for (var i = 0; i < it.length; i++) {
    if (it[i] !== last) {
      result.push(last = it[i])
    }
  }

  return result
}

비슷한데 뭔가 다름

배열에 푸시하는 방식이 새로움


'자료구조, 알고리즘 > Codewars 문제' 카테고리의 다른 글

Valid Braces ( 4 kyu )  (0) 2017.11.27
Who likes it? ( 6 kyu )  (0) 2017.11.27
Counting Duplicates ( 6 kyu )  (0) 2017.11.26
Vasya - Clerk ( 6 kyu )  (0) 2017.11.26
Build a pile of Cubes ( 6 kyu )  (0) 2017.11.25

+ Recent posts