Reverse Words in a String
question:
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.
1 class Solution { 2 public: 3 void reverseWord(string &s,int b,int e) //将字符串s中b-e之间的字串翻转 4 { 5 char temp; 6 while(b<e) 7 { 8 temp=s[b]; 9 s[b]=s[e]; 10 s[e]=temp; 11 b++; 12 e--; 13 } 14 } 15 void removeSpace(string &s) //去除字符串s首尾的空格,并将字符串中连续的多个空格变为一个 16 { 17 int i,j; 18 i=j=0; 19 int e=s.size(); 20 while(i<e&&s[i]==' ' ) i++; //去除字符串首部的空格,注意两个条件不能颠倒,因为s[e]超出字符串范围,会出错 21 if(i==e) {s.clear();return;} //当i==e时,表示字符串中只有空格,置原字符串为空 22 while(s[e-1]==' ') e--; //去除尾部的空格 23 while(i<e) 24 { 25 s[j]=s[i]; 26 i++; 27 while(i<e&&s[j]==' '&&s[i]==' ') i++; //去除连续的多个空格,若s[j]为空格,则下一位不能再为空格 28 j++; 29 if(i==e) break; 30 } 31 s.resize(j); 32 } 33 void reverseWords(string &s) { 34 removeSpace(s); 35 if(s.empty()||s.size()==1)return; //空字符串和长度为一的字符串不做处理 36 int b=0; 37 int e=s.size()-1; 38 reverseWord(s,b,e); //去除空格后的字符串整体翻转 39 b=e=0; 40 while(b!=s.size()-1) //将每个单词翻转 41 { 42 if(s[b]==' ') 43 { 44 b++; 45 e++; 46 continue; 47 } 48 else if(s[e]==' '||e==s.size()-1) 49 { 50 if(e==s.size()-1) //用if语句分开处理的原因是e不能为s.size(),否则s[e]越界 51 { 52 reverseWord(s,b,e); 53 break; 54 } 55 else 56 reverseWord(s,b,e-1); 57 b=e; 58 } 59 else 60 e++; 61 } 62 } 63 };
注:区分string类型和char *类型(字符数组),对于string类型的数据,用str[str.size()]!=‘\0'作为条件语句会出错,而char *类型不会
如:
1 #include<iostream> 2 #include<string> 3 using namespace std; 4 void main() 5 { 6 string str="hello"; 7 int i=0; 8 while(str[i]!='\0') 9 cout<<str[i++]; 10 }
程序报错:越界
1 #include<iostream> 2 #include<string> 3 using namespace std; 4 void main() 5 { 6 char *str="hello"; 7 int i=0; 8 while(str[i]!='\0') 9 cout<<str[i++]; 10 }
运行成功: