代码拉取完成,页面将自动刷新
package com.fishercoder.solutions;
/**
* 186. Reverse Words in a String II
Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Could you do it in-place without allocating extra space?
*/
public class _186 {
public static class Solution1 {
public void reverseWords(char[] s) {
// Three steps to reverse
// 1, reverse the whole sentence
reverse(s, 0, s.length - 1);
// 2, reverse each word
int start = 0;
for (int i = 0; i < s.length; i++) {
if (s[i] == ' ') {
reverse(s, start, i - 1);
start = i + 1;
}
}
// 3, reverse the last word, if there is only one word this will solve the corner case
reverse(s, start, s.length - 1);
}
private void reverse(char[] s, int start, int end) {
while (start < end) {
char temp = s[start];
s[start++] = s[end];
s[end--] = temp;
}
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。