/*
* 186. Reverse Words in a String II
Total Accepted: 14384
Total Submissions: 49577
Difficulty: Medium
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?
Related problem: Rotate Array
Hide Company Tags Amazon Microsoft Uber
Hide Tags String
Hide Similar Problems (M) Reverse Words in a String (E) Rotate Array
*/
public class ReverseWords {
public static void main(String[] args) {
ReverseWords rw = new ReverseWords();
String str = "the sky is blue";
char[] s = str.toCharArray();
System.out.println(str);
rw.reverseWords(s);
// System.out.println(String.valueOf(s));
}
// https://discuss.leetcode.com/topic/8366/my-java-solution-with-explanation
public void reverseWords(char[] s) {
// Two step to reverse
// 1, reverse the whole sentence
reverse(s, 0, s.length - 1);
System.out.println(String.valueOf(s));
// 2, reverse each word
int start = 0;
for (int i = 0; i <= s.length; i++) {
if (i == s.length || s[i] == ' ') {
System.out.println(i);
reverse(s, start, i - 1);
System.out.println(String.valueOf(s));
start = i + 1;
}
}
}
public void reverse(char[] s, int start, int end) {
while (start < end) {
char temp = s[start];
s[start] = s[end];
s[end] = temp;
start++;
end--;
}
}
}
186. Reverse Words in a String II
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Problem More LeetCode DiscussionsGiven an input string, r...
- Given an input string, reverse the string word by word. A...
- Given an input string, reverse the string word by word. A...
- 这道题有In place and non In place两种做法。in place的做法是,先把所有单词逐一翻转...
- My code: 之前做过类似的题目,但是用了额外空间。 希望这周有好运。 Anyway, Good luck, ...