Leecode 953. Verifying an Alien Dictionary[Easy]

题目描述

给定一个字符串数组和字典排序,这个字典序即外星人的字母顺序表,验证字符串数组是不是按照升序排列。

题解

写一个比较函数,然后两两验证。

class Solution {
public:
    // check if a is less than b
    bool check (string a, string b, unordered_map<char, int> &mp) {
        int size1 = a.length(), size2 = b.length();
        for (int i = 0; i < min(size1, size2); i++) {
            if (mp[a[i]] < mp[b[i]]) { // a is less than b
                return true;
            } else if (mp[a[i]] > mp[b[i]]) {
                return false;
            }
        }
        if (size1 < size2) {
            return true;
        }
        return false;
    }
    bool isAlienSorted(vector<string>& words, string order) {
        if (words.size() < 2) {
            return true;
        }
        // 给定一个字符顺序,判断出现的单词是否按照升序排列
        unordered_map<char, int> mp;
        for (int i = 0; i < order.length(); i++) {
            mp[order[i]] = i;
        }
        // cout << true <<  check("hello", "helloo", mp) << endl;
        // 两两比较
        for (int i = 1; i < words.size(); i++) {
            if (!(check(words[i - 1], words[i], mp))) { 
                return false;
            }
        }
        return true;
    }
};

需要注意的是,check函数,从左到右,如果有一个比对方大或者小,直接返回结果,不返回表示都一样,再判定长度即可,谁长谁大。

END.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值