题目描述
将一个英文语句以单词为单位逆序排放。例如“I am a boy”,逆序排放后为“boy a am I”
所有单词之间用一个空格隔开,语句中除了英文字母外,不再包含其他字符
输入描述:
将一个英文语句以单词为单位逆序排放。
输出描述:
得到逆序的句子
输入例子:
I am a boy
输出例子:
boy a am I
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while(in.hasNext()) { String str = in.nextLine(); char[] ch = str.toCharArray(); reverse(ch, 0, ch.length - 1); int start = 0; int end = start; while(start < ch.length) { while(end < ch.length && ch[end] != ' ') { end ++; } if(end == ch.length || ch[end] == ' ') { reverse(ch, start, end - 1); end ++; start = end; } } System.out.println(String.valueOf(ch)); } } public static void reverse(char[] ch, int start, int end) { while(start < end) { char temp = ch[start]; ch[start] = ch[end]; ch[end] = temp; start ++; end --; } } }