輸入描述
輸出描述
根據輸入,輸出查找到的兄弟單詞的個數
示例:
題目描述太過於複雜了,直接看輸入輸出案例比較好理解。
import java.util.Arrays;
import java.util.Scanner;
//尋找兄弟單詞
public class SearchBrotherwords {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()){
int n = sc.nextInt();
String[] str = new String[n];
String result = "";
for(int i = 0;i< n;i++){
str[i] = sc.next();
}
//將輸入的字符串存到字符串數組
Arrays.sort(str);
//將字符數組用Arrays.sort()方法 排序後存放 便於比較
String target = sc.next();
//輸入目標單詞
int k = sc.nextInt();
//要輸出第k個兄弟單詞
int count = 0;//計算兄弟單詞
for (int i = 0;i < n;i++){
if(Isfriend(target,str[i])){
//調用方法進行比較,如果是兄弟單詞,計數器+1
count += 1;
if(k == count){
//+到第k個兄弟單詞時 直接將兄弟單詞傳給result,便於後面輸出
result = str[i];
}
}
}
System.out.println(count+" ");
//輸出兄弟單詞數目
if(count >= k){
//判斷輸出第k個單詞
System.out.println(result);
}
}
}
//判斷是否是兄弟單詞的方法
private static boolean Isfriend(String S1, String S2){
boolean b = false;
if(S1.length() != S2.length()){
//長度不相等返回false
b = false;
}
if(S1.equals(S2)){
//equals判斷不相等 返回 false
b = false;
}else {
if(sort(S1).equals(sort(S2))){
//排序後相等返回true 這裏用了自己定義的sort排序方法
b = true;
}
}
return b;
}
//自己定義的排序方法
private static String sort(String str){
char[] s = str.toCharArray();
String result = "";
Arrays.sort(s);
for(int i = 0;i<s.length;i++){
result += s[i];
}
return result;
}
}