题目描述
小娴的男友小旭不幸患了一种怪病,这种怪病吞噬了他的大部分记忆,同时让他突然间不会书写符合正确语序的英文。神奇的是,虽然他写出的句子看上去杂乱无章,不过经过仔细分析可以发现,如果把单词的顺序倒过来,语法就是正确的了
尽管小旭忘记了很人很多事,但是他仍然记得小娴,仍然会记得给她用英文写情书。小娴被这份爱感动着,也不想放弃自己的爱人——然而她却无法读懂爱人的情书,因此要好心人帮她破译小旭的书信,你能帮帮她吗?
Input
第一行为n(1 <= n <= 100),表示测试用例的数目,接下来一共n行,每一行包含一个字符串。字符串长度不超过4000,单词与单词之间只用一个空格分隔,句末不会出现标点,句子前后不会出现任何多余的空格
Ootput
输出n行,每一行给出经过破译的字符串
输入示例
3
you love i
theatre the to went i week last
question a that's be, to not or be to
输出示例
i love you
last week i went to the theatre
to be or not to be, that's a question
思路
- 标点符号是和正确语序的那个单词连着的,因此无需特别处理,把它当作单词的一部分即可
- 把输入的字符串按空格分开,然后反序即可得到结果
package com.vapy.offer;
/**
*
* @author vapy 2016年9月28日
*
*/
import java.util.Scanner;
public class Main4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = 0;
if (sc.hasNextInt()) {
count = sc.nextInt();
sc.nextLine();
}
String[] input = new String[count];
for (int i = 0; i < count; i++) {
input[i] = sc.nextLine();
}
func(input);
for (String s : input) {
System.out.println(s);
}
}
public static void func(String[] input) {
for(int i = 0, len = input.length; i < len; i ++) {
input[i] = func2(input[i]);
}
}
public static String func2(String str) {
String[] temp = str.split(" ");
String result = "";
for (int i = temp.length - 1; i >= 0; i--) {
if (i == 0) {
result += temp[i];
}
else {
result = result + temp[i] + " ";
}
}
return result;
}
}
本文代码可在github查看:点击此处