scramble.js

Codewars 알고리즘 풀이


Problem

  • Complete the function that returns ‘true’ if a portion of ‘str1’ characters can be rearrange to match ‘str2’, otherwise returns ‘false’.
    • ‘str1’ 문자의 일부를 ‘str2’와 일치하도록 재배열할 수 있으면 ‘true’를 반환하고, 그렇지 않으면 ‘false’를 반환한다.
  • Only lower case letters will be used.
    • 소문자만 사용한다.
  • No punctuation or digits will be included.
    • 문자 부호나 숫자는 포함되지 않는다.



Solution 01

function scramble(str1, str2) {
  let arr1 = str1.split('').sort();
  let arr2 = str2.split('').sort();
  let x = 0;
  
  for (let i = 0; i < arr1.length; i++) {
    if (arr1[i] === arr2[x]) {
      x++;
    }
  }
  return x === arr2.length;
}

scramble('aloewlh', 'hello');  // true
scramble('rkqodlw', 'world');  // true
scramble('beceafd', 'code');   // false
scramble('atwabvo', 'wars');   // false


Solution 02

function scramble(str1, str2) {
  let obj = {};
  
  for (let i = 0; i < str1.length; i++) {
    if (!obj[str1[i]]) {
      obj[str1[i]] = 1;
    } else {
      obj[str1[i]]++;
    }
  }
  
  for (let i = 0; i < str2.length; i++) {
    if (!obj[str2[i]]) {
      return false;
    }
    
    if (obj[str2[i]] - 1 < 0) {
      return false;
    }
    obj[str2[i]]--;
  }
  return true;
}

scramble('aloewlh', 'hello');  // true
scramble('rkqodlw', 'world');  // true
scramble('beceafd', 'code');   // false
scramble('atwabvo', 'wars');   // false


Solution 03

function scramble(str1, str2) {
  let obj = {};
  
  if (str1.length < str2.length) return false;
  
  for (let i = 0; i < str2.length; i++) {
    obj[str2[i]] = str1.indexOf(str2[i], obj[str2[i]] ? obj[str2[i]] + 1 : 0);
    
    if (obj[str2[i]] < 0) {
      return false;
    }
  }
  return true;
}

scramble('aloewlh', 'hello');  // true
scramble('rkqodlw', 'world');  // true
scramble('beceafd', 'code');   // false
scramble('atwabvo', 'wars');   // false