您的位置:首页 > 编程语言 > C语言/C++

leetcode #151 in cpp

2016-06-29 10:28 344 查看
Solution:

1. reversed the whole string

2. reversed each word in the reversed string.

3. remove multiple space between words. 

Code:

class Solution {
public:
void reverseWords(string &s) {
if(s.empty()) return;
int head = 0;
int end = s.length() -1;
char temp;
//reverse the string
while(head<end){
temp = s[head];
s[head]= s[end];
s[end] = temp;
head++;
end --;
}

head = 0;
int temp_end;
//reverse each word in the reversed string
while(true){
while(head < s.length() && s[head] == ' '){
head++;
}
if(head >= s.length()) break;
end = head;
while(end < s.length() && s[end] != ' '){
end++;
}
end --;
temp_end = end;
while(head<end){
temp = s[head];
s[head] = s[end];
s[end] = temp;
head++;
end--;
}
head = temp_end + 1;
}

int cur = 0;
head = 0;
//reduce multiple " " between word.
while(head<s.length()){
if(s[head] != ' '){//move word to s[cur]. This step ensures that there are no multiple //spaces between words.
s[cur++] = s[head++];
}
else{//if we meet a " " at s[head],first find the next word
while(head < s.length() && s[head] == ' '){
head++;
}
if(head >= s.length()) break;
if(cur > 0){//if cur > 0, first append a " " at s[cur]. then append the word
s[cur] = ' ';
cur++;
}
}
}
s = s.substr(0,cur);

}

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