http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=92
import java.util.*; import java.lang.*; public class Main{ static String buffer[] ; static String[] words = new String[1000]; static String[] nonanagram = new String[1000]; static int wordsIndex=0; static int gramIndex =0; public static void main(String[] args) { Scanner k = new Scanner(System.in); while(k.hasNext()){ String dictionary = k.nextLine(); if(dictionary.equals("#")) break; buffer = dictionary.split(" "); for(int i=0 ; i<buffer.length ;i++){ if(buffer[i].equals(""))//如有連續兩個以上空格,會被記錄成"" continue; words[wordsIndex]=buffer[i]; wordsIndex++; } } record();//紀錄哪些不是anagram單字 print();//排列後顯示 } public static void record(){ boolean putIn =true; for(int i =0; i<wordsIndex ; i++){ putIn=true; if(words[i].length()==1){ nonanagram[gramIndex]=words[i]; gramIndex++; continue; } for(int j=0 ; j<wordsIndex ; j++){ if(words[i].equals(words[j])){ continue; } else if(words[i].length()==words[j].length()){ putIn=judge(words[i],words[j]);//判斷是否為anagram,再決定要不要放入 if(putIn==false)//是anagram,不放入 break; } } if(putIn){ nonanagram[gramIndex]=words[i]; gramIndex++; } } } public static boolean judge(String iWord , String jWord){ boolean putIn = true; String temp1 = iWord.toLowerCase(); char[] wordI = temp1.toCharArray(); String temp2 = jWord.toLowerCase(); char[] wordJ = temp2.toCharArray(); Arrays.sort(wordI);//按照ASCII碼,小 → 大 Arrays.sort(wordJ); temp1 = new String(wordI); temp2 = new String(wordJ); if(temp1.equals(temp2)) return false; else return true; } public static void print(){ for(int i=0 ; i<gramIndex ;i++) for(int j=i+1 ; j<gramIndex ;j++){ if(nonanagram[i].compareTo(nonanagram[j])>0){//compareTo()兩兩逐一比較ASCII code String temp = nonanagram[i]; nonanagram[i]=nonanagram[j]; nonanagram[j]=temp; } } for(int i=0 ; i<gramIndex; i++) System.out.println(nonanagram[i]); } }
沒有留言:
張貼留言