https://leetcode.com/problems/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?
这一题实际上比Reverse String那一题还要简单,如果in place的话,那一题还需要计算好提前量之类的东西。这一题给了一个很优厚的条件就是没有头尾空格而且保证每一个单词之间就相隔一个空格。那么实际算法就很简单了,先翻转整个字符串,然后再每个单词每个单词翻转,很标准的解法。。。
public void reverseRange(char[] s, int head, int tail){
int tmphead = head;
while(head < tail){
char tmp = s[head];
s[head] = s[tail];
s[tail] = tmp;
head++;
tail--;
}
}
public void reverseWords(char[] s) {
int head = 0, tail = s.length - 1;
reverseRange(s, head, tail);
int offset = head;
while(head <= tail){
int wordBegin = head;
while(head <= tail && s[head] != ' '){
head++;
}
head--;
reverseRange(s, wordBegin, head);
head += 2;
}
}
解决字符串操作问题,实现单词反转并保持原字符串中单词间的空格不变。
989

被折叠的 条评论
为什么被折叠?



