LeetCode 953. 验证外星语词典(C++、python)

本文介绍了一种算法,用于判断一组外星语单词是否按照给定的字母表顺序正确排序。通过将外星语字母映射到整数并比较单词序列,确保了外星语单词的字典序正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

某种外星语也使用英文小写字母,但可能顺序 order 不同。字母表的顺序(order)是一些小写字母的排列。

给定一组用外星语书写的单词 words,以及其字母表的顺序 order,只有当给定的单词在这种外星语中按字典序排列时,返回 true;否则,返回 false

 

示例 1:

输入:words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
输出:true
解释:在该语言的字母表中,'h' 位于 'l' 之前,所以单词序列是按字典序排列的。

示例 2:

输入:words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
输出:false
解释:在该语言的字母表中,'d' 位于 'l' 之后,那么 words[0] > words[1],因此单词序列不是按字典序排列的。

示例 3:

输入:words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"
输出:false
解释:当前三个字符 "app" 匹配时,第二个字符串相对短一些,然后根据词典编纂规则 "apple" > "app",因为 'l' > '∅',其中 '∅' 是空白字符,定义为比任何其他字符都小(更多信息)。

 

提示:

1 <= words.length <= 100

1 <= words[i].length <= 20

order.length == 26

在 words[i] 和 order 中的所有字符都是英文小写字母。

C++

class Solution {
public:
    bool isAlienSorted(vector<string>& words, string order) 
    {
        map<char,int> tmp;
        for(int i=0;i<order.size();i++)
        {
            tmp[order[i]]=i+1;
        }
        int n=words.size();
        for(int i=1;i<n;i++)
        {
            string s1=words[i-1];
            string s2=words[i];
            int m=min(s1.size(),s2.size());
            if(s1.size()>s2.size() && s1.substr(0,m)==s2)
            {
                return false;
            }
            for(int k=0;k<m;k++)
            {
                if(tmp[s1[k]]>tmp[s2[k]])
                {
                    return false;
                }
                else if(tmp[s1[k]]==tmp[s2[k]])
                {
                    continue;
                }
                else
                {
                    break;
                }
            }
        }
        return true;
    }
};

python

class Solution:
    def isAlienSorted(self, words: List[str], order: str) -> bool:
        dic={}
        for i in range(len(order)):
            dic[order[i]]=i+1
        n=len(words)
        for i in range(1,n):
            s1=words[i-1]
            s2=words[i]
            m=min(len(s1),len(s2))
            if len(s1)>len(s2) and s1[:m]==s2:
                return False
            for k in range(m):
                if dic[s1[k]]>dic[s2[k]]:
                    return False
                elif dic[s1[k]]==dic[s2[k]]:
                    continue
                else:
                    break
        return True

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值