Stop gninnipS My sdroW! CodeWars Kata

코드워즈에서 두 번째로 풀이한 문제입니다. Java 8 API를 최대한 이용하겠다는 의지를 불사르면서 문제를 풀어봅니다.

 

Stop gninnipS My sdroW!

사진: CodeWars

www.codewars.com/kata/5264d2b162488dc400000001

Details

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글자가 넘는 단어는 뒤집어서 출력해야 합니다.

 

My Solution

 

이번에는 Stream을 활용해서 문제를 풀어보았습니다. Stream 처리 메소드들이 익숙하지가 않아 forEach()를 이용해서 anonymous function을 만들어서 해결했네요.

단어 뒤집기 부분은 for문을 이용해서 글자 하나씩 StringBuffer로 밀어넣는 작업을 해주었습니다. Old School이네요.

package com.codewars;

import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class SpinWords {

    public String spinWords(String sentence) {
        StringBuffer sb = new StringBuffer();
        Stream<String> words = Arrays.stream(sentence.split(" "));
        words.forEach(item -> {
            if (item.length() >= 5) {
                for (int i = item.length() - 1; i >= 0; i--) {
                    sb.append(item.charAt(i));
                }
                sb.append(" ");
            } else {
                sb.append(item).append(" ");
            }

        });
        return sb.toString().strip();
    }
}

github.com/finewink/CodeWars-Maven/blob/30a6b12c922128bf1e85e58f184a910631e720a3/codewars/src/main/java/com/codewars/SpinWords.java

 

Best Practice

똑똑한 개발자분들은 map()함수를 이용해서 문제를 풀이했습니다. 그리고 가장 핵심이 되는 단어 뒤집기 부분은 StringBuilder().reverse()를 활용한 부분이 눈에 띕니다. 마지막으로 배열 합치기는 Stream의 collect() 메서드를 활용했네요.

public String bp(String sentence) {
        return Arrays.stream(sentence.split(" "))
                .map(i -> i.length() > 4 ? new StringBuilder(i).reverse().toString() : i)
                .collect(Collectors.joining(" "));
    }

 

728x90
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기