首页 > 试题广场 >

单词逆序

[编程题]单词逆序
  • 热度指数: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)
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)

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        String str=new Scanner(System.in).nextLine();
        String[] split = str.split(" ");
        StringBuilder res=new StringBuilder();
        for (int i = split.length-1; i >=0; i--) {
            if(i==0){
               res.append(split[i]);
            }else
            res.append(split[i]+" ");
        }
        System.out.println(res.toString());
    }
}

编辑于 2019-09-03 22:42:55 回复(0)