leetcode953. Verifying an Alien Dictionary

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011732358/article/details/84982062

题目链接
Easy题目
题目大意:自定义了一个字典序,用这个自定义的字典序判断数组中字符串是否是升序的。
示例:
输入 words = [“hello”,“leetcode”], order = “hlabcdefgijkmnopqrstuvwxyz”
输出 true
输入 words = [“word”,“world”,“row”], order = “worldabcefghijkmnpqstuvxyz”
输出 false
思路:用map来存储order的字典序,然后从words中逐个选取单词进行比较即可。

class Solution {
    public boolean isAlienSorted(String[] words, String order) {
        Map<Character, Integer> map = new HashMap<>();
        int len = words.length;
        int len_order = order.length();
        for(int i = 0; i < len_order; i++){
            map.put(order.charAt(i), i);
        }
        for(int i = 1; i < len; i++){
            if(!judge(words[i-1], words[i], map)){
                return false;
            }
        }
        return true;
    }
    public boolean judge(String str1, String str2, Map<Character, Integer> map){
        int len1 = str1.length();
        int len2 = str2.length();
        int i = 0;
        for(; i < len1 && i < len2; i++){
            if(map.get(str1.charAt(i)) < map.get(str2.charAt(i))){
                return true;
            }else if(map.get(str1.charAt(i)) > map.get(str2.charAt(i))){
                return false;
            }
        }
        if(i < len1){
            return false;
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/u011732358/article/details/84982062