Wednesday, March 23, 2016

LeetCode Q151: Reverse Words in a String

Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
class Solution {
public:
void reverseWords(string &s) {
if(s.length()==0)
return;
int p0=0; while(s[p0]==' '){p0++;}
int p1=s.length()-1; while(s[p1]==' '){p1--;}
if(p0<=p1)
s=s.substr(p0, p1-p0+1);
else{
s=s.substr(0, 0);
return;
}
p0=0;
p1=s.length()-1;
while(p0<p1){
char tmp=s[p0];
s[p0]=s[p1];
s[p1]=tmp;
p0++;
p1--;
}
p0=0; p1=0;
while(p1<=s.length()-1){
if(s[p1]!=' '){
s[p0]=s[p1];
p0++;
p1++;
continue;
}
s[p0]=s[p1];
p0++;
while(s[p1]==' '&&p1<=s.length()-1){p1++;}
}
s=s.substr(0, p0);
p0=0; p1=0;
while(p0<=s.length()-1){
p1=p0;
while(s[p1]!=' '&&p1<=s.length()-1){p1++;}
int nextp=p1;
p1--;
while(p0<p1){
char tmp=s[p0];
s[p0]=s[p1];
s[p1]=tmp;
p0++;
p1--;
}
p0=nextp+1;
}
}
};


Round 2 solution:
class Solution {
public:
void reverseWords(string &s) {
if(s.empty())
return;
int p0=0, p1=p0;
string tmps;
while(p0<s.length()){
if(!isspace(s[p0])&&(p0==0 || isspace(s[p0-1]))){
p1 = p0;
while(s[p1]!=' '&&p1!=s.length()) p1++;
int tmp = p1--;
string ss = s.substr(p0, p1-p0+1);
int p00=0, p11=ss.length()-1;
while(p00<p11) swap(ss[p00++], ss[p11--]);
tmps = tmps.empty()? ss: tmps+string(" ")+ss;
p0 = tmp;
}
p0++;
}
s=tmps;
reverse(s.begin(), s.end());
}
};
view raw Q151Rnd2.cpp hosted with ❤ by GitHub

No comments:

Post a Comment