翻转吧,字符串!

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27022241/article/details/82689401

                                           翻转吧,字符串!

(剑指Offter 面试题42)

    输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字符一样处理。例如输入字符串"I am a student.",则输出"student. a am I"。

/*
解题思路:
第一步,翻转句子中的所有字符
第二步,翻转每个单词中字符的顺序
*/
#include<iostream>
#include<string>
using namespace std;
void Reverse(string &s, int start, int end)  //将字符串s中位置为start至end的一段翻转
{
    while(start < end)
    {
        char c = s[start];
        s[start] = s[end];
        s[end] = c;
        start++;
        end--;
    }
}
string reverseSentence(string sentence)  //句子逆序
{
    int Size = sentence.size();   //句子字符个数
    Reverse(sentence, 0, Size-1); //翻转整个句子
    int start = 0, end = 0; 
    while(start < Size)
    {
        if(sentence[start] == ' ')  //start=end=' ',说明刚翻转完空格前的一个字符串
        {
            start++;
            end++;
        }
        else if(sentence[end] == ' ' || end == Size)  //end为空格或末尾,说明查找到一个单词,翻转
        {
            Reverse(sentence, start, end-1); //start指向单词的第一个字符,end指向最后一个字符后的空格
            start = end;
        }
        else  //end向下查找空格
        {
            end++;
        }
    }
    return sentence;
}

int main()
{
    string str;
    while(getline(cin,str))
    {
        string result = reverseSentence(str);
        cout<<result<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_27022241/article/details/82689401