您的位置:首页 > 其它

LeetCode - Reverse Words in a String

2014-03-18 03:13 351 查看
Reverse Words in a String

2014.3.18 03:09

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.

Solution:

  Reverse the whole string first, then reverse every single word. Redundant spaces must be skipped.

  Total time complexity is O(n). Space complexity is O(1).

Accepted code:

// 1TLE, 1AC, using another char[] is unnecessary. Don't miss '++i' or '++j'.
class Solution {
public:
void reverseWords(string &s) {
int i, j;
int len;
int offset;

// remove trailing spaces
while (s.length() > 0 && s[s.length() - 1] == ' ') {
s.pop_back();
}
len = (int)s.length();
if (len == 0) {
return;
}

// remove leading spaces
i = 0;
while (i < len && s[i] == ' ') {
++i;
}
s = s.substr(i, len - i);
len = (int)s.length();

// reverse the whole string
reverse(s, 0, len - 1);
// reverse every word
i = 0;
while (i < len) {
j = i;
while (j < len && s[j] != ' ') {
++j;
}
reverse(s, i, j - 1);
i = j;
while (i < len && s[i] == ' ') {
++i;
}
}

// remove redundant spaces between words
offset = 0;
i = 0;
while (true) {
j = i;
while (j < len && s[j] != ' ') {
s[j - offset] = s[j];
++j;
}
i = j;
if (i == len) {
break;
}
s[i - offset] = s[i];
++i;
while (i < len && s[i] == ' ') {
++i;
++offset;
}
}

while (offset > 0) {
s.pop_back();
--offset;
}
}
private:
void reverse(string &s, int ll, int rr) {
int i;
char ch;

for (i = ll; i < ll + rr - i; ++i) {
ch = s[i];
s[i] = s[ll + rr - i];
s[ll + rr - i] = ch;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: