OJ句子反转*python C++*

  • 题目描述
 给定一个句子(只包含字母和空格), 将句子中的单词位置反转,单词用空格分割, 单词之间只有一个空格,前后没有空格。 比如: (1) “hello xiao mi”-> “mi xiao hell
  • 输入描述
 输入数据有多组,每组占一行,包含一个句子(句子长度小于1000个字符)
  • 输出描述
 对于每个测试示例,要求输出句子中单词反转后形成的句子
  • 输入
 hello xiao mi
  • 输出
mi xiao hello 

python代码

words = []
words = input().split()
words.reverse()
print(" ".join(words))

C++代码

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int word_low[10000];
    int word_high[10000];
    string sentence;
    getline(cin, sentence);
    int index = 1;
    word_low[index] = 0;
    int i;
    for(i = 0;sentence[i] != '\0';i ++){
        if(sentence[i] == ' '){
            word_high[index] = i - 1;
            index ++;
            word_low[index] = i + 1;
            //cout << "low:" << word_low[index] << endl;

        }
    }
    word_high[index] = i - 1;
    for(i = index;i >= 1;i --){
        for(int j = word_low[i];j <= word_high[i];j ++){
            cout << sentence[j];
        }
        if(i != 1) cout << " ";
        else cout << endl;
    }
}

算法思想

识别空格,注意如果需要读入有空格的字符串,需要用到getline函数

猜你喜欢

转载自blog.csdn.net/weixin_36372879/article/details/81099061
今日推荐