首页 > 试题广场 >

单词逆序

[编程题]单词逆序
  • 热度指数:5121 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
对于一个字符串,请设计一个算法,只在字符串的单词间做逆序调整,也就是说,字符串由一些由空格分隔的部分组成,你需要将这些部分逆序。
给定一个原字符串A,请返回逆序后的字符串。例,输入"I am a boy!", 输出"boy! a am I"

输入描述:
输入一行字符串str。(1<=strlen(str)<=10000)


输出描述:
返回逆序后的字符串。
示例1

输入

It's a dog!

输出

dog! a It's
import java.util.Scanner;
public class Main{
    public static void main(String[] args) {
        String str = new Scanner(System.in).nextLine();
        String[] test = str.split(" ");
        for(int i = test.length - 1; i >= 0; i--) {
            System.out.print(test[i] + " ");
        } 
    }
}
编辑于 2019-09-08 13:12:18 回复(2)
#include<iostream>
#include<string>
using namespace std;
 
int main(int argc,const char* argv[])
{
    string str;
    getline(cin,str);
    int num = 0;
    const char* ptr = nullptr;
    string::reverse_iterator riter = str.rbegin();
    for( ; riter < str.rend() ; riter++)
    {
        if(*riter == ' ')
        {
            ptr = &(*(riter-1));
            for(int i=0 ; i < num ; i++,ptr++)
            {
                cout<<*ptr;
            }
            cout<<*riter;
            num = -1;
        }
        if(riter == str.rend()-1)
        {
            string::iterator iter = str.begin();
            for(int i=0 ; i < num+1 ; i++,iter++)
            {
                cout<<*iter;
            }
        }
        num++;
    }
    return 0;
}

我好菜啊,用一个指针记录正向输出位置,使用逆向迭代器实现翻转输出。。。还是知道题目只会有一个空格。。就不用了那么麻烦的判断了。。
编辑于 2019-09-25 15:47:28 回复(1)
print(' '.join(input().split()[::-1]))
编辑于 2019-09-04 16:01:25 回复(1)
print(' '.join(input().split()[::-1]))

发表于 2019-09-17 01:14:44 回复(0)
//整体思路是将单个的字符放进map里,并且要注意同属于一个单词的字符要放进同一个map里
//用string的连接特性将单个的字符连成单个的单词,
//最后再逆序遍历即可。

#include <iostream>
#include <map>
#include <algorithm>
#include <string>
using namespace std;

int main() {
    string str;
    map<int, string> m;//注意:这里必须是string而不能是char,否则就不能使用string的+连接
    //字符串的特性了
    getline(cin,str);
    auto cur = str.begin();
    int i, j;
    for(i = 0, j = 0; i < str.size(); ++i) {
        if( *cur == 32) {
            ++j;
        }
        if( *cur != 32) {
            m[j] += *cur; //注意:这里使用另一个变量j来保证字符能放到
//            一个key对应的value里,这样再使用+运算符将字符连接起来就水到渠成了
            
        }
        ++cur;
    }
    
    for (auto rpos = m.rbegin(); rpos != m.rend(); ++rpos) { //注意:
//    这里使用rbegin()、rend()来做到逆序遍历!
        
        cout << rpos->second << ' ';//这里另一种写法是cout >> *(rpos).second >> endl;
    }
    
    return 0;
}




发表于 2019-11-07 21:52:44 回复(0)
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
        string s;
        getline(cin,s);
        stringstream ss(s);
        string res=" ",tmp;
        while(ss>>tmp)
        {
            if(res==" ")
                res=tmp;
            else 
                res=tmp+" "+res;   
        }
    cout<<res<<endl;
}
发表于 2019-09-25 10:47:55 回复(0)
import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        String str_input = new Scanner(System.in).nextLine();
        String[] str_input_splits = str_input.split(" ");
        String str_output = "";
        for(int i=(str_input_splits.length-1); i>=0; i--){
            if(str_output == ""){
               str_output += str_input_splits[i]; 
            }else{
               str_output = str_output + " " + str_input_splits[i];   
            }
        }
        System.out.println(str_output);
    }
}

发表于 2019-09-04 20:13:51 回复(2)
#include<iostream>
#include<vector>
using namespace std;
int main()
{
    vector<string> a;
    string b;
    while(cin>>b)
    {
        a.push_back(b);
    }
    for(int i=a.size();i--;i>0)
    {
        cout<<a[i]<<" ";
    }
}

发表于 2019-09-02 16:43:54 回复(7)
#include<stdio.h>  
#include <stdlib.h>
//三步翻转法,第一步分出来每个单词,第二步翻转每个单词,第三步翻转整个句子
  void reverseWord(char *start, char *end)  
{   
    char temp;
    while(start < end)  
    {  
        temp=*start ;  
        *start = *end;  
        *end = temp; 
        *start++;
        *end--; 
    }  
}
  
int main() {
   char s[10000] = " ";      
   char *p=s;
   char *q=s;
    
    gets(s);
    
   while(*q != '\0')
   {
        if(' ' == *q)            //单词结尾:q首次遇到空格(此时将单词头地址p,和单词尾地址q-1) 
        {
              reverseWord(p,q-1); 
              while(' ' == *q ) //单词开头:q跳若干空格后下一单词首字符 
              { 
                   q++;
              }
              p=q;              //单词头地址赋值给p 
        }
        else
        {
             q++;               //单词内部地址自加 
        }
   }
   reverseWord(p,q-1);          //将最后一个单词逆序 
   reverseWord(s,q-1);          //将整句话逆序 
   printf("%s\n", s); 
   return 0;  
}

发表于 2019-09-10 21:04:51 回复(8)
functiontest(str){
str = str.split(' ').reverse().join(' ')
return str
}
为什么通不过啊
编辑于 2019-09-10 10:47:25 回复(6)
function sor(str){
    let arr = [];
    arr = str.split(' ').reverse();
    print(arr.join(' '))
}
sor(readline())
下边的好像还快一些
function sor(str){
    let arr = [];  
    let arr2 = [];
    arr = str.split(' ');
    for(let v of arr){
        arr2.unshift(v);
    }
    print(arr2.join(' '))
}
sor(readline())



编辑于 2019-09-09 10:39:12 回复(0)
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

//字符串局部逆序
void reverse(int begin,char*str,int sz){
    int i;
    for(i=0;i<sz/2;i++){
        char ch = str[begin + i];
        str[begin + i] = str[begin+sz-1-i];
        str[begin+sz-1-i] = ch;
    }
}
int main(){
    char s[10000] = {"hello world 123."};
    gets(s);

    int sz = strlen(s);

    //hello world 123.
    reverse(0, s, strlen(s));
    int i;
    //printf("%s\n",s);
    int begin = 0;
    for(i=0;i<sz;i++){
        if(s[i] == ' '){
            //printf("%d %d\n",begin, i - begin);
            reverse(begin, s, i - begin);
            begin = i+1;
            //printf("%s\n",s);
        }
    }
    if(begin){
        reverse(begin, s, i - begin);
    }else{
        reverse(0, s, strlen(s));
    }

    printf("%s\n",s);
    //begin = i+1;
    return 0;
}

编辑于 2020-08-02 20:54:15 回复(0)
str.split(" ").reverse().join(" ")
发表于 2020-01-22 00:17:24 回复(1)
#include<iostream>
#include<string>
#include <sstream>
using namespace std;
int main()
{
	string str;
	getline(cin,str);
	int Memory = str.length()-1;
    for (int i= str.length();i>=0;i--)
    {
        if (str[i] == ' ')
        {
        	if (Memory == str.length()-1)
        	{
        		cout << str.substr(i+1,Memory-i);
        		Memory = i;
			}
			else
			{
				cout << str.substr(i,Memory-i+1);//Core!
				Memory = i ;
			}
    	}
    	if ( i == 0)
    	{
    		cout << str.substr(i,Memory-i);
		}
	}
	return 0;
}

发表于 2019-10-26 04:48:32 回复(0)
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class Main {
    public static void main(String[] args){
        String s = new Scanner(System.in).nextLine();
        List<String> arr1 = new ArrayList<String>();
        Collections.addAll(arr1,s.split(" "));
        Collections.reverse(arr1);
        String re = String.join(" ",arr1);
        System.out.println(re);
    }
}

发表于 2019-10-24 17:54:31 回复(0)
#include<iostream>
#include<vector>
#include<string>

using namespace std;
int main(){
    while(1){
        string s;
        getline(cin,s);
        vector<string>ss;
        string temp="";
        string out="";
        for(int i=0;i<s.size();i++){
            if(s[i] != ' '){
                temp += s[i];
            }
            else{
                ss.push_back(temp);
                temp.clear();
            }
        }
        ss.push_back(temp);
        while(!ss.empty()){
            cout<<ss.back()<<' ';
            ss.pop_back();
        }
    }
    return 0;
}

发表于 2019-10-22 10:07:09 回复(0)
有没有用OC开发的啊
发表于 2019-10-21 20:18:38 回复(0)
#include <iostream>
#include <string.h>
using namespace std;
void Re(string& str)
{
    int i=0,t=0,n=str.length();
    cout << "n=" << n <<endl;
    for(i=0;i<n/2;i++)
    {
        t=str[i];
        str[i]=str[n-i-1];
        str[n-i-1]=t;
    }
}
void Local(string &str,int left,int right)
{
    int n=right-left+1;
    for(int i=0;i<n/2;i++)
    {
        int t=str[left+i];
        str[left+i]=str[right-i];
        str[right-i]=t;
    }
}
int main()
{
    string str;
    int i;
    int left=0,right;
    getline(cin,str);
    Re(str);
    cout << str << endl;
    for(i=0;i<=str.length();i++)
    {
        if(str[i]==' '||i==str.length())
            {
                int right=i-1;
                Local(str,left,right);
                left=right+2;
            }

    }
    cout << str << endl;

}

发表于 2019-10-15 11:01:28 回复(0)
str = input()
list_str = str.split(" ")
for i in range(len(list_str)-1,-1,-1):
    print(list_str[i],end=" ")

发表于 2019-10-14 14:10:07 回复(0)
#include <iostream>
#include <cstring>

using namespace std;
/*
 * 将从j到k的字符逆序
 */
void reverse(char str[], int jint k)
{
   char s;
   while (j < k)
   {
      s = str[j];
      str[j] = str[k];
      str[k] = s;
      j++;
      k--;
   }
}

int main()
{
   char str[100000];
   cin.get(str, 100000); //将整个字符串读入数组

   int n = strlen(str); //找出最后一位字符位置,给最后一位字符后面加一个空格,确保每一个单词后面有一个空格
   str[n + 1] = str[n];
   str[n] = ' ';

   long i = 0;
   long j = 0;
   for (i = 0; i <= n; i++) //每一个空格前面是一个单词,将单词逆序
   {
      if (str[i] == ' ')
      {
         reverse(str, j, i - 1);
         j = i + 1;
      }
   }

   for (j = n - 1; j >= 0; j--) //逆序输出整个字符串,因为单词逆序了,所以输出的单词都是正序
   {
      cout << str[j];
   }
   return 0;
}
//比较笨,写的很麻烦,哈哈

发表于 2019-10-12 17:18:08 回复(0)