哈工大2020軟件構造Lab2 Problem1.4 Graph Poet 思路

哈工大2020軟件構造Lab2

Problem1.4 Graph Poet

問題簡述:給定一組單詞(文件輸入),對於兩個相鄰的單詞a和b,認爲存在一條由a到b的有向邊,通過Graph接口構造有向圖。再給定一由單詞組成的句子,如果句子中兩個相鄰單詞之間在Graph圖中有一箇中間單詞則將中間單詞插入到兩單詞之間(如果有多個則插入權重最大的那個)

讀入單詞

  • 使用文件輸入
  • 參考文章

  • String.split()分割爲數組
  • 通過String.toLowerCase()小寫化

核心1:構建圖

  • 要求:相鄰的單詞加邊
  • 首先要在加邊前通過Graph.add()加點
graph.add(words[i].toLowerCase());
  • 加邊時要判斷是否存在:由於Graph.set()能返回之前加的邊的值,以此來判斷是否存在,存在則在之前的值加一(之前的邊的值保存爲lastEdgeWeight
int lastEdgeWeight = graph.set(words[i - 1].toLowerCase(), words[i].toLowerCase(), 1);
if (lastEdgeWeight != 0)
	graph.set(words[i - 1].toLowerCase(), words[i].toLowerCase(), lastEdgeWeight + 1);
  • n個點加n-1條邊for (int i = 0; i < words.length; i++)

核心2:擴展Poem

  • for (int i = 1; i < words.length; i++)
  • 當相鄰兩個單詞任意一個不在之前創建的圖裏,則將後者單詞加入即可(再加個空格)
if (!vertices.contains(words[i - 1].toLowerCase()) || !vertices.contains(words[i].toLowerCase())) {
	answer += " " + words[i];
	continue;
}
  • 當存在時,由於Bridge長度只能爲2,所以:
  • 分別求兩個單詞的sourcestargets
  • 將該Map轉換爲Set求交集
intersection = sources.keySet();
intersection.retainAll(targets.keySet());
  • 若交集爲空,則無橋
  • 若交集不空,則在交集中找最短的橋(可以在Map的value中查詢weight)
for (String key : intersection) {
	if (sources.get(key) + targets.get(key) > maxBridge) {
		maxBridge = sources.get(key) + targets.get(key);
		bridge = key;
	}
}
  • 最後加入新生成的Poem
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章