标签:style blog color io os ar for sp div
其他版本还有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
标签:style blog color io os ar for sp div
原文地址:http://www.cnblogs.com/jilichuan/p/3997389.html