LeetCode2—String字符串中单词翻转

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".

Clarification:

  • 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;  
}  
};  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值