CS-Notes/docs/notes/58.1 翻转单词顺序列.md
2019-11-02 17:33:10 +08:00

55 lines
1.5 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 58.1 翻转单词顺序列
[NowCoder](https://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3?tpId=13&tqId=11197&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
## 题目描述
```html
Input:
"I am a student."
Output:
"student. a am I"
```
## 解题思路
题目应该有一个隐含条件就是不能用额外的空间虽然 Java 的题目输入参数为 String 类型需要先创建一个字符数组使得空间复杂度为 O(N)但是正确的参数类型应该和原书一样为字符数组并且只能使用该字符数组的空间任何使用了额外空间的解法在面试时都会大打折扣包括递归解法
正确的解法应该是和书上一样先旋转每个单词再旋转整个字符串
```java
public String ReverseSentence(String str) {
int n = str.length();
char[] chars = str.toCharArray();
int i = 0, j = 0;
while (j <= n) {
if (j == n || chars[j] == ' ') {
reverse(chars, i, j - 1);
i = j + 1;
}
j++;
}
reverse(chars, 0, n - 1);
return new String(chars);
}
private void reverse(char[] c, int i, int j) {
while (i < j)
swap(c, i++, j--);
}
private void swap(char[] c, int i, int j) {
char t = c[i];
c[i] = c[j];
c[j] = t;
}
```
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-2.png"></img></div>