Java机试题:查找兄弟单词(使用正则以及不使用正则的思路)

描述

定义一个单词的“兄弟单词”为:交换该单词字母顺序(注:可以交换任意次),而不添加、删除、修改原有的字母就能生成的单词。 兄弟单词要求和原来的单词不同。例如: ab 和 ba 是兄弟单词。 ab 和 ab 则不是兄弟单词。 现在给定你 n 个单词,另外再给你一个单词 str ,让你寻找 str 的兄弟单词里,按字典序排列后的第 k 个单词是什么? 注意:字典中可能有重复单词。本题含有多组输入数据。   数据范围:1 \le n \le 1000 \1≤n≤1000 ,输入的字符串长度满足 1 \le len(str) \le 10 \1≤len(str)≤10  , 1 \le k < n \1≤k<n 

输入描述:

先输入单词的个数n,再输入n个单词。 再输入一个单词,为待查找的单词x 最后输入数字k

输出描述:

输出查找到x的兄弟单词的个数m 然后输出查找到的按照字典顺序排序后的第k个兄弟单词,没有符合第k个的话则不用输出。
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

/**
 * 
 * 思路:找到兄弟单词。兄弟单词的判断条件:长度相等,两个词不一样,包含的字符要一样,包含的个数要一样,利用正则判断。【不使用正则的判断思路:这里还可以将字符串中的字母进行排序,然后对比单词是否一样判断,这里我用正则判断】
 * 有重复的,所以不用treeSet来排序,用 Collections.sort(brother);
 *
 */
public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
    
        while (in.hasNextInt()) {
            int num = in.nextInt();
            List<String> all = new ArrayList<String>();
            for (int i = 0; i < num; i++) { 
                all.add(in.next());
            }
            String word = in.next();
            int outIndex = in.nextInt() - 1;
            List<String> brother = new ArrayList<String>();
            for (int i = 0; i < all.size(); i++) {
                String temp = all.get(i);
                if(checkBrother(word,  temp)) {
                    brother.add(temp);
                };
            }
            Collections.sort(brother);
            System.out.println(brother.size());
            if(brother.size() > outIndex) {
                System.out.println(brother.get(outIndex));
            }
            
        }

        
        
    }

    private static boolean checkBrother(String word, String temp) {
        boolean match = true;
        if(temp.length() == word.length() && !temp.equals(word)) {
            for (int j = 0; j < word.length(); j++) {
                char tempChar = word.charAt(j);
                if(temp.indexOf(word.charAt(j))< 0 || temp.replaceAll("[^"+tempChar+"]","").length() !=  word.replaceAll("[^"+tempChar+"]","").length()) {
                    match = false;
                    break;
                }
            }
        } else {
            match = false;
        }
        return match;
        
    }
}

 

上一篇:C++:时间日期类,增加若干秒


下一篇:koa对密码进行加密并且存到数据库