您的位置:首页 > 其它

Leetcode: Reverse Words in a String

2014-03-15 20:43 603 查看
Given an input string, reverse the string word by word.

For example,

Given s = "
the sky is blue
",

return "
blue is sky the
".

click to show clarification.

Clarification:

What constitutes a word?

A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?

Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?

Reduce them to a single space in the reversed string.
最新加上的题,原理比较简单,两次翻转,但实现起来需要注意边界用例。因为可能多个空格,所以先分割单词会比较好。
class Solution {
public:
void reverseWords(string &s) {
int size = s.size();
int start = 0, end = 0;

string word;
int i = 0;
while (i < size) {
if (s[i] == ' ' && start < i) {
// Abstract word and reverse
word = s.substr(start, i - start);
reverseWord(word);
for (int idx = 0; idx < word.size(); ++idx) {
s[end++] = word[idx];
}
s[end++] = ' ';
}
while (s[i] == ' ' && i + 1 < size && s[i+1] == ' ') {
++i;
}
if (s[i] == ' ') {
start = i + 1;
}
++i;
}
if (start < size) {
word = s.substr(start, i - start);
reverseWord(word);
for (int idx = 0; idx < word.size(); ++idx) {
s[end++] = word[idx];
}
}

// Eliminate the trailing space
if (s[end-1] == ' ') {
--end;
}

s = s.substr(0, end);
reverseWord(s);
}

void reverseWord(string &word) {
char tmp;
for (int i = 0, j = word.size() - 1; i < j; ++i, --j) {
tmp = word[i];
word[i] = word[j];
word[j] = tmp;
}
}
};
=======================第二次=========================
<pre name="code" class="cpp">class Solution {
public:
void reverseWords(string &s) {
int cur = 0;
int word_start = 0;
int i = 0;
while (i < s.size()) {
if (s[i] == ' ' && (cur == 0 || s[i-1] == ' ')) {
++i;
}
else {
if (s[i] == ' ') {
reverse(s, word_start, cur - 1);
word_start = cur + 1;
}
s[cur++] = s[i++];
}
}

--cur;
if (cur > 0) {
if (s[cur] == ' ') {
--cur;
}
else {
reverse(s, word_start, cur);
}
}

reverse(s, 0, cur);
s = s.substr(0, cur + 1);
}

void reverse(string &s, int start, int end) {
char tmp;
for (; start < end; ++start, --end) {
tmp = s[start];
s[start] = s[end];
s[end] = tmp;
}
}
};


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode string