1. 程式人生 > >華為OJ訓練之0040-170114-句子逆序(單詞倒排)

華為OJ訓練之0040-170114-句子逆序(單詞倒排)

題目

將一個英文語句以單詞為單位逆序排放。例如“I am a boy”,逆序排放後為“boy a am I”
所有單詞之間用一個空格隔開,語句中除了英文字母外,不再包含其他字元

介面說明
/**
* 反轉句子
*
* @param sentence 原句子
* @return 反轉後的句子
*/
public String reverse(String sentence);

知識點 陣列
執行時間限制 10M
記憶體限制 128
輸入
將一個英文語句以單詞為單位逆序排放。
輸出
得到逆序的句子
樣例輸入 I am a boy
樣例輸出 boy a am I

==========================================

一次通過 100分

單詞倒排【中級】
一次通過 200分

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {


        Scanner scanner=new Scanner(System.in);
        String str=scanner.nextLine();

        String word=new String();
        for
(int i=str.length()-1;i>=0;i--) { char c=str.charAt(i); if(c!=' ') {word+=c;} else { for(int j=word.length()-1;j>=0;j--) {System.out.print(word.charAt(j));} System.out.print(" "); word=new
String(); } } for(int j=word.length()-1;j>=0;j--) {System.out.print(word.charAt(j));} } }

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {


        Scanner scanner=new Scanner(System.in);
        String str=scanner.nextLine();

        String word=new String();
        for(int i=str.length()-1;i>=0;i--)
        {
            char c=str.charAt(i);
            if(('a'<=c&&c<='z')||('A'<=c&&c<='Z')) {word+=c;}
            else
            {
                for(int j=word.length()-1;j>=0;j--)
                {System.out.print(word.charAt(j));}
                System.out.print(" ");
                word=new String();
            }

        }

        for(int j=word.length()-1;j>=0;j--)
        {System.out.print(word.charAt(j));}

    }

}