题目
题目描述
给定一个字符串,逐个翻转字符串中的每个单词。
示例:
输入: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
输出: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
注意:
单词的定义是不包含空格的一系列字符
输入字符串中不会包含前置或尾随的空格
单词与单词之间永远是以单个空格隔开的
进阶:
使用 O(1) 额外空间复杂度的原地解法
作者:珺王不早朝
链接:https://www.jianshu.com/p/9d624882d786
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
方法1:翻转
public void reverseWords(char[] str) {
int i = 0;
for (int j = 0; j < str.length; j++) {
if (str[j] == ' ') {
reverse(str, i, j);
i = j + 1;
}
}
reverse(str, i, str.length);
System.out.println(String.valueOf(str));
reverse(str, 0, str.length);
}
private void reverse(char[] ch, int l, int r) {
for (int k = l; k < (l + r) / 2; k++) {
char tmp = ch[k];
int g = r - 1 - k + l;
ch[k] = ch[g];
ch[g] = tmp;
}
}