2022-5-17 每日一题-leetcode

题目链接:https://leetcode.cn/problems/verifying-an-alien-dictionary/

个人题解:哈希表,遍历,检查前一个和后一个是否按照字典序排列。

代码:

class Solution {
    unordered_map<char,int> hash;
public:
    bool judge(string &a,string &b){
        int n=a.length(),m=b.length();
        for(int i=0;i<n && i<m;i++){
            if(hash[a[i]]>hash[b[i]]) return false;
            else if(hash[a[i]]<hash[b[i]]) return true;
        }
        return n<=m;
    }
    
    bool isAlienSorted(vector<string>& words, string order) {
        for(int i=0;i<order.size();i++) hash[order[i]]=i;
        for(int i=0;i<words.size()-1;i++){
            if(!judge(words[i],words[i+1])) return false;
        }
        return true;
    }
};

运行截图:

image

posted @ 2022-05-18 13:58  黑VS白-清墨  阅读(47)  评论(0)    收藏  举报