150強訪談簡單

重建行程

「重建行程」問題的詳細指南和 Python 實作。

問題陳述

簡單

您將獲得一份機票列表,其中 Tickets[i] = [from_i, to_i] 代表一個航班的出發機場和到達機場。按順序重構行程並返回。

所有門票均屬於從「甘迺迪」出發的一名男子。因此,行程必須以“JFK”開頭。

如果有多個有效行程,則應傳回作為單一字串讀取時詞彙順序最小的行程。例如,行程 ['JFK', 'LGA'] 的詞彙順序比 ['JFK', 'LGB'] 更小。

您可以假設所有門票至少形成一個有效行程。所有門票必須使用一次且僅限一次。

寫一個函數 findItinerary(tickets: List[List[str]]) -> List[str]

約束條件
  • 1 <= len(tickets) <= 300
  • tickets[i].length == 2
  • from_i.length == 3
  • to_i.length == 3
  • from_i and to_i consist of uppercase English letters

範例

Example 1
Input
tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]
Output
["JFK","MUC","LHR","SFO","SJC"]
Explanation

The only valid itinerary is JFK -> MUC -> LHR -> SFO -> SJC.

Example 2
Input
tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output
["JFK","ATL","JFK","SFO","ATL","SFO"]
Explanation

Another possible reconstruction is JFK -> SFO -> ATL -> JFK -> ATL -> SFO, but it is larger lexically.

Need a Hint?
考慮使用高階圖特定的資料結構,例如集合或堆疊。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。