LeetCode:5400. 旅行终点站

https://leetcode-cn.com/problems/destination-city

给你一份旅游线路图,该线路图中的旅行线路用数组 paths 表示,其中 paths[i] = [cityAi, cityBi] 表示该线路将会从 cityAi 直接前往 cityBi 。请你找出这次旅行的终点站,即没有任何可以通往其他城市的线路的城市。

题目数据保证线路图会形成一条不存在循环的线路,因此只会有一个旅行终点站。

 

示例 1:

输入:paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]]
输出:"Sao Paulo" 
解释:从 "London" 出发,最后抵达终点站 "Sao Paulo" 。本次旅行的路线是 "London" -> "New York" -> "Lima" -> "Sao Paulo" 。
示例 2:

输入:paths = [["B","C"],["D","B"],["C","A"]]
输出:"A"
解释:所有可能的线路是:
"D" -> "B" -> "C" -> "A". 
"B" -> "C" -> "A". 
"C" -> "A". 
"A". 
显然,旅行终点站是 "A" 。
示例 3:

输入:paths = [["A","Z"]]
输出:"Z"
 

提示:

1 <= paths.length <= 100
paths[i].length == 2
1 <= cityAi.length, cityBi.length <= 10
cityAi != cityBi
所有字符串均由大小写英文字母和空格字符组成。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/destination-city
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路:用列表拼接旅游线路,,不断更新,直到列表中只剩一条线路(见代码与注释)

class Solution(object):
    def destCity(self, paths):
        """
        :type paths: List[List[str]]
        :rtype: str
        """
        while(True):
            line = []  # 拼接所走城市
            # 更新line
            for path in paths:
                cityA, cityB = path[0], path[-1]
                try:
                    try:
                        i = line.index(cityA)
                        line[i+1:i+1] = path[1:]
                    except:
                        j = line.index(cityB)
                        line[j:j] = path[:-1]
                except ValueError:
                    line.append('#')
                    line.extend(path)
            # 如果完全连通,结束拼接,也就是全部走完
            if '#' not in line[1:]:
                break
            # 更新paths
            paths, j = [], []
            for i in line[1:]:
                if i is '#':
                    paths.append(j)
                    j = []
                else:
                    j.append(i)
            paths.append(j)
        return line[-1]

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值