题目如下:

You are given some lists of regions where the first region of each list includes all other regions in that list.

Naturally, if a region X contains another region Y then X is bigger than Y.

Given two regions region1region2, find out the smallest region that contains both of them.

If you are given regions r1r2 and r3 such that r1 includes r3, it is guaranteed there is no r2 such that r2 includes r3.

It's guaranteed the smallest region exists.

Example 1:

Input:
regions = [["Earth","North America","South America"],
["North America","United States","Canada"],
["United States","New York","Boston"],
["Canada","Ontario","Quebec"],
["South America","Brazil"]],
region1 = "Quebec",
region2 = "New York"
Output: "North America"

Constraints:

  • 2 <= regions.length <= 10^4
  • region1 != region2
  • All strings consist of English letters and spaces with at most 20 letters.

解题思路:首先递归找出region1所属的regions链,并保持结果;然后再递归查找region2所属的regions链,找到第一个region在region1所属的regions链即可。

代码如下:

class Solution(object):
def findSmallestRegion(self, regions, region1, region2):
"""
:type regions: List[List[str]]
:type region1: str
:type region2: str
:rtype: str
"""
dic = {}
for region in regions:
parent = region[0]
for i in range(1,len(region)):
dic[region[i]] = parent dic_region1 = {}
while region1 in dic:
dic_region1[region1] = 1
region1 = dic[region1] while region2 in dic:
if region2 in dic_region1:
return region2
region2 = dic[region2]
return regions[0][0]

最新文章

  1. 基于netty http协议栈的轻量级流程控制组件的实现
  2. [转]Python 字符串操作实现代码(截取/替换/查找/分割)
  3. 打开hibernate文件报警告
  4. iOS UIButton setTitle与setAttributedTitle
  5. 移动端打印调试插件 - debug.js 介绍
  6. 从官方ROM中提取原生APK
  7. cxf(3.1.1) 异常Caused by: java.io.FileNotFoundException: class path resource [META-INF/cxf/cxf-extension-soap.xml]
  8. Jump Game II
  9. 在VSTO界面中,调用xll中的函数
  10. (转)myrepo
  11. 决策树简单介绍(二) Accord.Net中决策树的实现和使用
  12. android WebView, WebChromeClient和WebViewClient加载网页基本用法
  13. 机器学习 1、R语言
  14. 转 git操作小结
  15. R语言RJava安装步骤
  16. [LeetCode116]Path Sum
  17. MR-join连接1......
  18. 《生命》第三集:Mammals (哺乳动物)
  19. HTTP协议07-通用首部字段
  20. jquery-json 插件使用方法

热门文章

  1. NOIp2018D1T1 积木大赛 【思维】
  2. MSF魔鬼训练营-3.3.2 口令猜测与嗅探
  3. PTA(Basic Level)1053.住房空置率
  4. java使用顺序数组实现二叉树
  5. 怎么快速写好看的手机menu菜单
  6. 数据结构之单链表的实现-java
  7. Codeforces 1201C. Maximum Median
  8. 9.用ExecuteSqlCommand执行存储过程
  9. Auto-increment 自动增长
  10. ion-icon