1 回答

TA貢獻1856條經驗 獲得超11個贊
我認為實現算法的關鍵是選擇正確的數據結構。我認為正確的數據結構是Map。鍵Map
將是Integer
(因為鍵不能是原語,所以它不能是int
),它將是字母的索引,值將是在該索引處具有相關字母的單詞列表。
這是我根據您詳細說明的規范和限制實現該算法的代碼。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HangsMan {
? ? public static void main(String[] args) {
? ? ? ? String[] words = new String[]{"fish", "look", "flow", "fowl", "cool", "eel", "poll", "fill"};
? ? ? ? char letter = 'l';
? ? ? ? Map<Integer, List<String>> theMap = new HashMap<>();
? ? ? ? Integer key;
? ? ? ? List<String> value;
? ? ? ? for (String word : words) {
? ? ? ? ? ? int ndx = word.indexOf(letter);
? ? ? ? ? ? int last = word.lastIndexOf(letter);
? ? ? ? ? ? if (last == ndx + 1) {
? ? ? ? ? ? ? ? ndx += 1_000_000;
? ? ? ? ? ? }
? ? ? ? ? ? key = Integer.valueOf(ndx);
? ? ? ? ? ? if (theMap.containsKey(key)) {
? ? ? ? ? ? ? ? value = theMap.get(key);
? ? ? ? ? ? }
? ? ? ? ? ? else {
? ? ? ? ? ? ? ? value = new ArrayList<String>();
? ? ? ? ? ? ? ? theMap.put(key, value);
? ? ? ? ? ? }
? ? ? ? ? ? value.add(word);
? ? ? ? }
? ? ? ? theMap.forEach((k, v) -> System.out.println(v));
? ? }
}
請注意,雙字母單詞會在索引中添加 1_000_000(一百萬),以便將它們與單字母單詞分開。因此, “poll”一詞的索引將為 1,000,002,而“ cold”一詞的索引僅為 2。
你問我為什么要加一百萬?因為,根據維基百科,英語中最長的單詞包含189,819 個字母。
添加回答
舉報