import java.util.Arrays; import java.util.Scanner; /** * 字母重排 * @author NEU-2015 * */ public class Demo { public static void main(String[] args) { Scanner input = new Scanner(System.in); String str; String[] words; String[] sort; String[] NeedFindWord; char[] charArray; boolean flag; while (input.hasNext()) { str = input.nextLine(); //读取字典中的字符串 words = str.split(" "); str = input.nextLine(); //读取要查找的字符 Arrays.sort(words); //给所有的单词排序 sort = new String[words.length]; for(int i = 0; i < words.length; i++) { //将words赋值到sort中 然后将sort中每个单词的字母排序 sort[i] = words[i]; } for(int i = 0; i < sort.length; i++) { //给每一个单词排序 charArray = sort[i].toCharArray(); Arrays.sort(charArray); sort[i] = String.valueOf(charArray); } NeedFindWord = str.split(" "); for(int i = 0; i < NeedFindWord.length; i++) { //给要查找的每一个单词中的字母进行排序 for(int j = 0; j < NeedFindWord[i].length(); j++) { charArray = NeedFindWord[i].toCharArray(); Arrays.sort(charArray); NeedFindWord[i] = String.valueOf(charArray); } } for(int i = 0 ; i < NeedFindWord.length; i++) { //查找 flag = false; for(int j = 0; j < sort.length; j++) { if(sort[j].equals(NeedFindWord[i])) { if(j == 0) { System.out.print(words[j]); } System.out.print(" " + words[j]); flag = true; } } if(!flag) { //找不到输出-1 System.out.print(-1); } System.out.println(); } } } }
问题描述:输入一个字典,然后再输入若干单词,每输入一个单词W,都需要在字典中找到所有可以用w的字母重拍后得到的单词,并按照字典序从小到大的顺序排科ubucunz输出-1
测试数据
targ given score refund only trap word carn course pepper part
resco nfudre aptr sctt oresuc
输出结果
score
refund
part trap
-1
course
时间: 2024-10-26 21:11:43