首页 > 代码库 > leetcode Reverse Words in a String
leetcode Reverse Words in a String
#include <cstdlib>
#include <string>
#include <algorithm>
using namespace std;
void reverseWords(string &s) {
string rs ;
for(int i = s.length()-1; i >= 0; ){
while(s[i] == ‘ ‘ && i >= 0)
i--;
if(i < 0){
break;
}
if(!rs.empty())
rs.push_back(‘ ‘);
string t;
while(s[i] != ‘ ‘ && i>=0)
t.push_back(s[i--]);
reverse(t.begin(),t.end());
rs.append(t);
}
s = rs;
}
int main(int argc, char** argv) {
string s = "a b cd";
reverseWords(s);
cout<<s;
return 0;
}
其他版本还有C的:
#include <cstdlib>
#include <string>
#include <algorithm>
using namespace std;
void reverseWords(string &s) {
const char * src = s.c_str();
if(src == NULL)
return;
int len = 0;
bool flag = false;
while(src[len] != ‘\0‘){
if(src[len] != ‘ ‘)
flag = true;
len++;
}
if(flag == false){
s = string();
return;
}
if(len == 0)
return;
char * result ;
result[0] = ‘\0‘;
for(int i = len - 1; i >=0; ){
while(src[i] == ‘ ‘ && i >= 0)
i--;
if(i < 0)
break;
if(strlen(result) != 0)
strcat(result," ");
int wordlen = 0;
while(src[i] != ‘ ‘ && i >= 0){
wordlen++;
i--;
}
char * tmp = (char*)malloc(sizeof(char)*(wordlen+1));
int j = i+1;
for(j = i+1; j < i+1+wordlen; j++)
tmp[j-i-1] = src[j];
tmp[wordlen] = ‘\0‘;
strcat(result,tmp);
}
if(strlen(result) == 0)
s = string();
else
s = result;
}
int main(int argc, char** argv) {
string s = "a";
reverseWords(s);
cout<<s.length()<<endl;
cout<<s;
return 0;
}
leetcode Reverse Words in a String