您的位置:首页 > 其它

Leetcode-151.Reverse Words in a String

2015-12-30 03:42 246 查看
Problem Description:

Given an input string, reverse the string word by word.

For example,

Given s = ” the sky is blue “,

return “blue is sky the”.

Analysis:

This is probably by far the most common string manipulation interview question.

The idea to solve the problem is : First delete all the extra spaces, then reverse all the characters in the string, then reverse the letters of each word. For trim job, we need to pointers.

O(1) space solution :

class Solution {
public:
void reverseWords(string& s) {
trim(s);//remove the whitespace and reverse.
int l = 0;
for (int i = 0; i < s.size(); ++i)
{
if (s[i] == ' ')
{
reverse(s.begin() + l, s.begin() + i);
l = i + 1;
}
}
reverse(s.begin() + l, s.end());// we need one more operation to reverse the last word. OR  we could add a extra ' ' to the end, delete it when finish.
return;
}

void trim (string& s)
{
int i;
int n = s.size();
for (i = n - 1; i >= 0 && s[i] == ' '; --i){}
s = s.substr(0, i + 1);
reverse(begin(s), end(s));
for (i = s.size() - 1; i >= 0 && s[i] == ' '; --i){}
s = s.substr(0, i + 1);
n = s.size();
int tail = 0;
for (i = 0; i < n;)
{
if (s[i] != ' ' || (s[i] == ' ' && s[i - 1] != ' '))
s[tail++] = s[i];
i++;
}
s = s.substr(0, tail);// remove the traling spaces or  s.resize(tail);
return ;
}
};


Other short code :

O(N) both space and time complexity

void reverseWords(string &s) {
istringstream is(s);
string tmp;
is >> s;
while(is >> tmp) s = tmp + " " + s;
if(s[0] == ' ') s = "";
}


Python code

def reverseWords1(text):
print " ".join(reversed(text.split()))
print " ".join(text.split()[::-1])
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: