In an alien language, surprisingly they also use english lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters.

Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographicaly in this alien language.



Example 1:

Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
Output: true
Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.
Example 2:

Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
Output: false
Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.
Example 3:

Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"
Output: false
Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).


Constraints:

1 <= words.length <= 100
1 <= words[i].length <= 20
order.length == 26
All characters in words[i] and order are English lowercase letters.

这题也不难,直接按题意来进行了,可以先对字符串内的字符根据order来做个映射再做处理。

class VerifyingAnAlienDictionary : public Solution {
public:
    void Execute() {
        std::cout << "Case 1: " << isAlienSorted(vector<string>{"hello","leetcode"}, "hlabcdefgijkmnopqrstuvwxyz") << std::endl;
        std::cout << "Case 2: " << isAlienSorted(vector<string>{"word","world","row"}, "worldabcefghijkmnpqstuvxyz") << std::endl;
        std::cout << "Case 3: " << isAlienSorted(vector<string>{"apple","app"}, "abcdefghijklmnopqrstuvwxyz") << std::endl;
    }
    bool isAlienSorted(const vector<string>& words, string order) {
        int cor[26] = {0};
        int index = 0;
        for (auto c : order) {
            cor[c - 'a'] = ++index;
        }

        for (std::size_t i = 1; i < words.size(); i++) {
            bool same = true;
            std::size_t compareSize = words[i - 1].size() < words[i].size() ? words[i - 1].size() : words[i].size();
            for (std::size_t j = 0; j < compareSize; j++) {
                if (cor[words[i - 1][j] - 'a'] > cor[words[i][j] - 'a']) {
                    return false;
                }
                if (cor[words[i - 1][j] - 'a'] < cor[words[i][j] - 'a']) {
                    same = false;
                    break;
                }
            }
            if (same && words[i - 1].size() > words[i].size()) {
                return false;
            }
        }

        return true;
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day