LeetCode 557. Reverse Words in a String III

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.

这题是要reverse一个被空格分割的句子里每个单词。刚开始想的是split by space生成一个string数组然后每个string reverse以后拼一起。但也可以采取和541类似的思想,找到分割字符串的条件和要reverse的index,直接对charArray进行操作。

undefined - undefined - LeetCode

class Solution {
    public String reverseWords(String s) {
        char[] charArray = s.toCharArray();
        int n = s.length();
        int i = 0;
        int left = i;
        int right = i;
        while (i < n) {
            if (charArray[i] == ' ') {
                right = i - 1;
                reverse(charArray, left, right);
                left = i + 1;
            }
            i++;
        }
        reverse(charArray, left, n - 1);
        return new String(charArray);
    }

    private void reverse(char[] array, int i, int j) {
        while (i <= j) {
            char temp = array[i];
            array[i] = array[j];
            array[j] = temp;
            i++;
            j--;
        }
    }
}

你可能感兴趣的:(LeetCode,leetcode)