题目描述:
对字符串中的所有单词进行倒排。
说明:
1、每个单词是以26个大写或小写英文字母构成;
2、非构成单词的字符均视为单词间隔符;
3、要求倒排后的单词间隔符以一个空格表示;如果原字符串中相邻单词间有多个间隔符时,倒排转换后也只允许出现一个空格间隔符;
4、每个单词最长20个字母;
输入描述:
输入一行以空格来分隔的句子
输出描述:
输出句子的逆序
import java.util.ArrayList;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
String s = scanner.nextLine();
int startIndex = 0;
int endIndex = 0;
ArrayList<String> list = new ArrayList<>();
while (endIndex < s.length())
{
char startch = s.charAt(startIndex);
char endch = s.charAt(endIndex);
if (Character.isLetter(startch))
{
while (endIndex < s.length() && Character.isLetter(s.charAt(endIndex)))
{
endIndex++;
}
list.add(s.substring(startIndex, endIndex));
while (endIndex < s.length() && !Character.isLetter(s.charAt(endIndex)))
{
endIndex++;
}
startIndex = endIndex;
endIndex = startIndex;
}
else
{
startIndex++;
endIndex = startIndex;
}
}
for (int i = list.size() - 1; i >= 1; i--)
System.out.print(list.get(i) + " ");
System.out.println(list.get(0));
}
}
}
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
String s = scanner.nextLine();
char[] s1 = s.toCharArray();
String s2 = "";
for (int i = 0; i < s1.length; i++)
{
if (!((s1[i] >= 'a' && s1[i] <= 'z') || (s1[i] >= 'A' && s1[i] <= 'Z')))
{
s1[i] = ' ';
}
s2 += s1[i];
}
String[] str = s2.split("\\s+");
for (int i = str.length - 1; i > 1; i--)
{
System.out.print(str[i] + " ");
}
if (str[0].length() == 0)
{
System.out.println(str[1]);
}
else
{
System.out.println(str[1] + " " + str[0]);
}
}
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
String str = scanner.nextLine();
String sTmp = "";
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < str.length(); i++)
{
if ((str.charAt(i) >= 'a' && str.charAt(i) <= 'z') || (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z'))
{
sTmp += str.charAt(i);
}
else
{
if (!sTmp.equals(""))
{
list.add(sTmp);
sTmp = "";
}
else
{
continue;
}
}
}
if (!sTmp.equals(""))
{
list.add(sTmp);
sTmp = "";
}
for (int i = list.size() - 1; i >= 1; i--)
{
System.out.print(list.get(i) + " ");
}
System.out.println(list.get(0));
}
}
}