【牛客網】查找兄弟單詞

題目鏈接

在這裏插入圖片描述

在這裏插入圖片描述


一個小坑:題目中要求輸出第x個兄弟單詞。需要判斷一下,如果這個數x太大了,就不輸出。

package May16;

import java.util.*;

/**
 * 有40%的通過率,我考慮可能是 單詞書中不儲存 相同的單詞?試一下
 * 不是這個原因,錯在,題目中要求輸出第x個兄弟單詞。需要判斷一下,如果這個數x太大了,就不輸出。
 */
public class Demo11 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int i = in.nextInt();// 保存一共有多少單詞
            String[] arr = new String[i];// 保存單詞。
//            HashSet<String> set = new HashSet<>();
            for (int j = 0; j < i; j++) {
                String str = in.next();
//                if (!set.contains(str)) {
                arr[j] = str;
//                    set.add(str);
//                }
            }
            Arrays.sort(arr);// 字典排序
            // 成功進行排序
            String toFind = in.next();// 接收字符串
            int toFindInt = in.nextInt();// 接收序號
            int total = 0;
            LinkedList<String> list = new LinkedList<>();
            for (int j = 0; j < i; j++) {
                if (judge(toFind, arr[j])) {
                    total++;
                    list.add(arr[j]);
                }
            }
            System.out.println(total);
            if (toFindInt <= list.size())
            System.out.println(list.get(toFindInt - 1));

        }

    }

    // 判斷兩個字符串是否是兄弟字符串。
    public static boolean judge(String str1, String str2) {
        if (str1 == null || str2 == null) return false;
        if (str1.length() != str2.length()) {
            return false;
        }
        if (str1.equals(str2)) return false;
        char[] chars1 = str1.toCharArray();
        char[] chars2 = str2.toCharArray();
        Arrays.sort(chars1);
        Arrays.sort(chars2);
        for (int i = 0; i < chars1.length; i++) {
            if (chars1[i] != chars2[i]) {
                return false;
            }
        }
        return true;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章