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

[Codewars] Stop gninnipS My sdroW!

by 줍 2024. 6. 8.

Q. Write a function that takes in a string of one or more words, and returns the same string, but with all words that have five or more letters 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.

 

"Hey fellow warriors"  --> "Hey wollef sroirraw" 

"This is a test        --> "This is a test" 

"This is another test" --> "This is rehtona test"

 

S.

String spinWords(String str) {
  List<String> result = [];
  for (final word in str.split(' ')) {
    if (word.length >= 5) {
      result.add(word.split('').reversed.join());
    } else {
      result.add(word);
    }
  }
  return result.join(' ');
}

 

+

map 함수 써보기. swift는 고차함수가 {클로저} 형태로 쓰이지만 다트함수에서는 (익명 함수) 형태로 쓰인다.

String spinWords(String str) {
  return str
    .split(' ')
    .map((word) => word.length >= 5 ? word.split('').reversed.join() : word)
    .join(' ');
}

'알고리즘 > Codewars' 카테고리의 다른 글

[Codewars] Find The Parity Outlier  (1) 2024.06.09
[Codewars] You're a square!  (0) 2024.06.09
[Codewars] Multiples of 3 or 5  (0) 2024.06.06
[Codewars] Mumbling  (0) 2024.06.04
[Codewars] Get the Middle Character  (0) 2024.06.04