본문 바로가기
알고리즘/Codewars

[Codewars] Stop gninnipS My sdroW! (6 kyu) / JavaScript

by fluss 2022. 11. 5.

https://www.codewars.com/kata/5264d2b162488dc400000001

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present.

 

Examples:

spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw" 
spinWords( "This is a test") => returns "This is a test" 
spinWords( "This is another test" )=> returns "This is rehtona test"
 

설명:

하나 이상의 문자열을 받고 같은 문자열이지만 5개 이상의 글자는 뒤집힌 문자열을 반환하는 함수를 작성하세요. 글자와 공백으로만 구성된 문자열이 전달됩니다. 공백은 두 단어 이상일 때만 포함됩니다.

 

예시:

spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw" 
spinWords( "This is a test") => returns "This is a test" 
spinWords( "This is another test" )=> returns "This is rehtona test"

 

풀이

문자열을 공백을 기준으로 나눈 배열을 만들고 반복문으로 배열의 원소의 길이가 5이상이면 그 글자를 뒤집어서 다시 저장하였다.

 

코드

function spinWords(string){
  string = string.split(' ');
  for(let i = 0; i < string.length; i++){
    if(string[i].length >= 5) string[i] = string[i].split('').reverse().join('');
  }
  return string.join(' ');
}

댓글