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
".
- What constitutes a word?
A sequence of non-space characters constitutes a word. - Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces. - How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
实现过程比较简单,但是一开始如果忘记了string的一些用法就比较麻烦,整理一下String类的一些常用函数:
int capacity()const; //返回当前容量(即string中不必增加内存即可存放的元素个数)
int size()const; //返回当前字符串的大小
int length()const; //返回当前字符串的长度
bool empty()const; //当前字符串是否为空
getline(istream &in,string &s);用于从输入流in中读取字符串到s中,以换行符'\n'分开。
string &operator=(const string &s);//把字符串s赋给当前字符串
string &assign(const string &s);//把字符串s赋给当前字符串
string &operator+=(const string &s);//把字符串s连接到当前字符串的结尾
string &append(const char *s); //把c类型字符串s连接到当前字符串结尾
string &append(const char *s,int n);//把c类型字符串s的前n个字符连接到当前字符串结尾
string &append(const string &s); //同operator+=()
bool operator==(const string &s1,const string &s2)const;//比较两个字符串是否相等 运算符">","<",">=","<=","!="均被重载用于字符串的比较;
int compare(const string &s) const;//比较当前字符串和s的大小
string substr(int pos = 0,int n = npos) const;//返回pos开始的n个字符组成的字符串
int find(char c, int pos = 0) const;//从pos开始查找字符c在当前字符串的位置
string &insert(int p0, const char *s);
iterator erase(iterator first, iterator last);//删除[first,last)之间的所有字符,返回删除后迭代器的位置
class Solution {
public:
void reverseWords(string & s)
{
string ss;
int i = s.length()-1;
while(i>=0)
{
while(i>=0&&s[i] == ' ')
{
i --;
}
if(i<0) break;
if(ss.length()!=0)
ss.push_back(' ');
string temp ;
for(;i>=0&&s[i]!=' ';i--)
temp.push_back(s[i]);
reverse(temp.begin(),temp.end());
ss.append(temp);
}
s=ss;
}
};