题目描述

牛客网

题目描述

  1. Input:
  2. "I am a student."
  3. Output:
  4. "student. a am I"

解题思路

先翻转每个单词,再翻转整个字符串。

题目应该有一个隐含条件,就是不能用额外的空间。虽然 Java 的题目输入参数为 String 类型,需要先创建一个字符数组使得空间复杂度为 O(N),但是正确的参数类型应该和原书一样,为字符数组,并且只能使用该字符数组的空间。任何使用了额外空间的解法在面试时都会大打折扣,包括递归解法。

  1. public String ReverseSentence(String str) {
  2. int n = str.length();
  3. char[] chars = str.toCharArray();
  4. int i = 0, j = 0;
  5. while (j <= n) {
  6. if (j == n || chars[j] == ' ') {
  7. reverse(chars, i, j - 1);
  8. i = j + 1;
  9. }
  10. j++;
  11. }
  12. reverse(chars, 0, n - 1);
  13. return new String(chars);
  14. }
  15. private void reverse(char[] c, int i, int j) {
  16. while (i < j)
  17. swap(c, i++, j--);
  18. }
  19. private void swap(char[] c, int i, int j) {
  20. char t = c[i];
  21. c[i] = c[j];
  22. c[j] = t;
  23. }