[Algo] 84. Reverse Words In A Sentence I

Reverse the words in a sentence.

Assumptions

  • Words are separated by single space

  • There are no heading or tailing white spaces

Examples

  • “I love Google” → “Google love I”

Corner Cases

  • If the given string is null, we do not need to do anything.
public class Solution {
  public String reverseWords(String input) {
    // Write your solution here
    char[] charArr = input.toCharArray();
    swap(charArr, 0, charArr.length - 1);
    int start = 0;
    for (int i = 0; i < charArr.length; i++) {
      if (charArr[i] != ' ' && (i == 0 || charArr[i - 1] == ' ')) {
        start = i;
      }
      // just check i instead of i + 1 for edge
      if (charArr[i] != ' ' && (i == charArr.length - 1 || charArr[i + 1] == ' ')) {
        swap(charArr, start, i);
      }
    }
    return new String(charArr);
  }

  private void swap(char[] charArr, int left, int right) {
    while (left < right) {
      char tmp = charArr[left];
      charArr[left] = charArr[right];
      charArr[right] = tmp;
      left += 1;
      right -= 1;
    }
  }
}
原文地址:https://www.cnblogs.com/xuanlu/p/12777316.html