LeetCode - Verifying an Alien Dictionary

04.08.2021

小白一枚,文章仅当日记本记录学习进度 ;)

如被浏览,请多多指教,非常感谢大家纠错与建议!

(因留学顺便练习英语,所以部分用英文笔记,并无他意) 


This is Facebook most asked question in 2020 and 2021, this is a sub-task of another Hard problem 'Alien Dictionary' which is much simpler. (ps: 一位YouTuber是这样说的但是我真的花了好多功夫才弄明白要干嘛...对我来说感觉难点不在解题本身,而在读懂题目-_-)

Solution - Hashtable (Python)

https://www.youtube.com/watch?v=OVgPAJIyX6o

Runtime: 24 ms, faster than 99.15% of Python3 online submissions for Verifying an Alien Dictionary.

Memory Usage: 14.4 MB, less than 17.15% of Python3 online submissions for Verifying an Alien Dictionary.

1. Iterate over the alien order and put character and index into a Hashmap. 

list = [(i,j) for i, j in enumerate(mylist)] --> [(1, 2), (3, 4), ...]
dict = {i:j for i, j in enumerate(mylist)]   --> {a:b, c:d, ...}

2. 可以开始比较index,如果是按照外星人的字典顺序,需要满足w1[i] < w2[i].

举个例子,w1=app, w2=apple,前三个字母一样,w1[3]=None, w2[3]=l, 可以看做空小于字母l,所以是满足条件的,但如果反过来那么条件w2比w1短就不满足条件了,所以有了第一个if condition: If we reach the end of w2 before we reach the w1, then it means w2 is the prefix of w1 which is not allowed. 

第二个if condition就比较字母的index大小就可以了,如果不满足条件,return False,如果满足条件我们不能保证一定符合条件因为可能input里面有其他单词需要查看,所以break当前的for loop就可以了

class Solution:
    def isAlienSorted(self, words: List[str], order: str) -> bool:
        dictInd = {char:ind for ind, char in enumerate(order)} # [pair for pair in enumerate(mylist)]
        
        for i in range(len(words)-1):
            w1, w2 = words[i], words[i+1]
            
            for j in range(len(w1)):
                # If we reach the end of w2 before we reach the w1, then it means w2 is the prefix of w1 which is not allowed
                if j == len(w2):
                    return False
                if w1[j] != w2[j]:
                    if dictInd[w1[j]] > dictInd[w2[j]]:
                        return False
                    break
                    # if it is True we can't directly say it because we still need to check remaining chars 
                    # but we can at least break this for loop
        return True

Solution - (Java)

https://www.youtube.com/watch?v=qSbJZWENtX4


Facebook|117

Walmart Labs|10

Amazon|3

eBay|3

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值