본문으로 바로가기

Description

공백으로 단어들이 구분되어 있는 문자 배열의 각 단어를 반전시키는 문제입니다.

Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Example 2:

Input: s = "God Ding"
Output: "doG gniD"

Constraints:

  • 1 <= s.length <= 5 * 104
  • s contains printable ASCII characters.
  • s does not contain any leading or trailing spaces.
  • There is at least one word in s.
  • All the words in s are separated by a single space.

Solution 1. Reverse() 활용

public String reverseWords(String s) {
        
    char[] c = s.toCharArray();
    int start = 0;
    for (int i = 0; i < c.length; i++) {
        if(c[i] == ' '){
            reverse(c,start,i-1);   //공백 전까지 단어 revese 후 다음 단어 시작 index 설정
            start = i+1;
        }else if(i==c.length-1){ //마지막 char까지 reverse
            reverse(c,start,i);
        }
    }
    return new String(c);

}

public void reverse(char[] chars, int start, int end){

    while(start < end){
        char temp = chars[start];
        chars[start++] = chars[end];
        chars[end--] = temp;
    }
}

두개의 포인터를 이용한 reverse 메서드를 구현하여 활용하는 방법입니다. 단어의 시작점부터 공백 전까지 길이를 계산하여 단어를 추출한 뒤 구현한 reverse메서드에 넣어 반전 시켜줍니다.

Reference

 

Reverse Words in a String III - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com