本文共 2329 字,大约阅读时间需要 7 分钟。
题目,找出单词表中每个单词只有一个字母不同的所有单词(简单版,花费时间多)
import java.util.ArrayList;
import java.util.List; import java.util.Map; import java.util.TreeMap; public class WordMap { //如果一个单词具有minWords个或更多个通过1字母替换得到的单词,则输入 public static void printHighChangeables(Map<String, List<String>> adjWords, int minWords){ for(Map.Entry<String, List<String>> entry:adjWords.entrySet()){//该用法见上一条博客 List<String> words=entry.getValue(); if(words.size()>=minWords){ //输出key值,单词数量和value值 System.out.print(entry.getKey()+" "); System.out.print(words.size()+"):"); for(String w:words){ System.out.print(" "+w); } System.out.println(); } } } //检测两个单词时候只在一个字母上不同 private static boolean oneCharOff(String word1,String word2){ if(word1.length()!=word2.length()){ return false; } int diffs=0; for(int i=0;i<word1.length();i++){ if(word1.charAt(i)!=word2.charAt(i)){ if(++diffs>1){ return false; } } } return diffs==1; } //输入一串单词的集合,得到符合两个单词时候只在一个字母上不同的map对象, //map的key代表当前单词,value是满足要求的所有值。 public static Map<String, List<String>> computeAdjacentWords(List<String> theWords){ Map<String,List<String>> adjWords=new TreeMap<>(); String[] words=new String[theWords.size()]; //用toArray将集合转储为一个数组,避免了重复调用以使从object //向String转换,如果使用泛型那么它将发生在幕后 theWords.toArray(words); for(int i=0;i<words.length;i++){ for(int j=i+1;j<words.length;j++){ if(oneCharOff(words[i],words[j])){ //一次就相互都存储一下,避免重复遍历 update(adjWords,words[i],words[j]); update(adjWords,words[j],words[i]); } } } return adjWords; } //跟新map private static <KeyType> void update(Map<KeyType, List<String>> m, KeyType key,String value){ List<String> lst=m.get(key); if(lst==null){//如果不存在,就创建一个集合 lst=new ArrayList<>(); m.put(key, lst); } //如果存在,直接加到尾部 lst.add(value); } }测试:
public static void main(String[] args) {
// TODO Auto-generated method stub List<String> list=null; String[] a=new String[]{"dine","line","mine","pine","vine","wide","wife","wipe","wire"}; list=Arrays.asList(a); Map<String,List<String>> m=WordMap.computeAdjacentWords(list); for(Map.Entry<String,List<String>> me : m.entrySet()) { System.out.println(me.getKey() + ": " + me.getValue()); } }结果:
dine: [line, mine, pine, vine]
line: [dine, mine, pine, vine] mine: [dine, line, pine, vine] pine: [dine, line, mine, vine] vine: [dine, line, mine, pine] wide: [wife, wipe, wire] wife: [wide, wipe, wire] wipe: [wide, wife, wire] wire: [wide, wife, wipe]转载地址:http://qvjqi.baihongyu.com/