题目描述

给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。

示例 1:

输入: "Let's take LeetCode contest"
输出: "s'teL ekat edoCteeL tsetnoc" 

注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。

思路

分割字符串,再逆序,拼接到字符串

代码实现

package String;

/**
 * 557. Reverse Words in a String III(反转字符串中的单词 III)
 * 给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
 */
public class Solution557 {
    public static void main(String[] args) {
        Solution557 solution557 = new Solution557();
        String s = "Let's take LeetCode contest";
        System.out.println(solution557.reverseWords(s));
    }

    /**
     * 分割字符串,再逆序,拼接到字符串
     *
     * @param s
     * @return
     */
    public String reverseWords(String s) {
        String[] words = s.split(" ");
        StringBuilder sb = new StringBuilder();
        int len = words.length;
        if (words.length == 1) {
            return reverseString(s);
        }
        for (int i = 0; i < len - 1; i++) {
            sb.append(reverseString(words[i]) + " ");
        }
        sb.append(reverseString(words[len - 1]));
        return String.valueOf(sb);
    }

    public String reverseString(String s) {
        char[] chars = s.toCharArray();
        int i = 0;
        int j = chars.length - 1;
        while (i < j) {
            char temp = chars[i];
            chars[i] = chars[j];
            chars[j] = temp;
            i++;
            j--;
        }
        return new String(chars);
    }
}