reverseWords.js (8kyu 19)

Codewars 알고리즘 풀이


Description

  • Complete the solution so that it reverses all of the words within the string passed in.
    • 문자열 내 모든 단어를 역순으로 반환한다.



Solution 01

function reverseWords(str) {
  const arr = str.split(' ');
  let result = [];
  
  for (let i = arr.length - 1; i >= 0; i--) {
    result.push(arr[i]);
  }
  
  return result.join(' ');
}

reverseWords('Codewars');      // Codewars
reverseWords('Hello World');   // World Hello
reverseWords('How are you?');  // you? are How


Solution 02

function reverseWords(str) {
  return str.split(' ').reverse().join(' ');
}

reverseWords('Codewars');      // Codewars
reverseWords('Hello World');   // World Hello
reverseWords('How are you?');  // you? are How