题解 | #查找兄弟单词#

查找兄弟单词

http://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68

import java.util.*;
import java.util.stream.Collectors;

public class Main{
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        String[] split = str.split(" ", -1);
        if(split.length<=3){
            System.out.println(0);
        }else{
            List<String> list = new ArrayList<>(Arrays.asList(split));
            list.remove(0);
            int k = Integer.parseInt(list.remove(list.size()-1));
            List<String> cc = cc(list);
            System.out.println(cc.size());
            if(cc.size()>=k){
                System.out.println(cc.get(k-1));
            }
        }
    }

    public static List<String> cc(List<String> list){
        List<String> pList = new ArrayList<>();
        paiLeiStr(list.get(list.size()-1).toCharArray(),pList,list.get(list.size()-1),0);
        return list.parallelStream().filter(pList::contains).sorted().collect(Collectors.toList());
    }

    public static void paiLeiStr(char[] str,List<String> result,String temp,int i){
        if(i==str.length){
            String s = new String(str);
            if(!s.equals(temp)){
                result.add(s);
            }
            return;
        }
        for(int k=i;k<str.length;k++){
            swap(str,k,i);
            paiLeiStr(str,result,temp,i+1);
            swap(str,k,i);
        }
    }
    
    public static void swap(char[] c,int s,int e){
        char temp = c[s];
        c[s] = c[e];
        c[e] = temp;
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务