leetcode151. Reverse Words in a String

17 篇文章 0 订阅

medium程度题

题目:

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

难度在于给定字符串中空格连续出现的次数不限定

如Given s = "   I   love you 365 days ha ha ",

则return "ha ha days 365 you love I".

我的想法是把所有夹在空格之间的子串提取出来放在一个容器中,最后再相加。

AC代码(效率不高):

class Solution 
{
public:
    void reverseWords(string &s) 
    {
        do
        {
            if(s.empty())
                break;
                
            vector<string> vec_result;
            int i = 0 , j = 0;
            while(s[i] != '\0')
            {
                while(s[i] == ' ')
                    i++; //第一个不为空格的字符
                j = i;
                while(s[i] != ' '&&s[i] != '\0')
                    i++; //s[i]指向一个子串的尾部
                if (i > j) //如果i>j 则i,j之间含有一个子串
                {
                    string temp;
                    temp.assign(s,j,i - j);
                    vec_result.push_back(temp);
                }
            }
            
            s.erase();
            int size = vec_result.size();
            if (size == 0)
                break;
            
            for (int m = size -1;m >= 1;m--) //把容器中的字符串相加......
                s = s + vec_result[m] + " ";
            s += vec_result[0];
        }while(false);
    }
};


OMG,比较粗暴。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值