953.Verifying an Alien Dictionary(Map)

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.

使用Map将字典序映射为数字,进行比较

class Solution {
    public boolean compare(Map<Character,Integer> ch,String string1,String string2){
        int len1 = string1.length();
        int len2 = string2.length();
        int len = len1 < len2 ?len1:len2;
        for(int i =0;i<len;i++){
            if(ch.get(string1.charAt(i)) < ch.get(string2.charAt(i)))  return true;
            else if(ch.get(string1.charAt(i)) == ch.get(string2.charAt(i)))
                continue;
            else
                return false;
        }
        if(len1<=len2)   return true;
        else    return false;
    }
    public boolean isAlienSorted(String[] words, String order) {
        Map<Character,Integer> ch = new HashMap<Character,Integer>();
        for(int i =0;i<order.length();i++){
            ch.put(order.charAt(i),i);
        }
        for(int i=1;i<words.length;i++){
            if(!compare(ch,words[i-1],words[i])) return false;
        }
        return true;
    }
}
posted @ 2019-01-17 21:15  御心飞行  阅读(211)  评论(0编辑  收藏  举报