美文网首页
LeetCode 1160. 拼写单词 java

LeetCode 1160. 拼写单词 java

作者: 烛火的咆哮 | 来源:发表于2019-11-18 16:47 被阅读0次

    给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars

    假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。

    注意:每次拼写时,chars 中的每个字母都只能用一次。

    返回词汇表 words 中你掌握的所有单词的 长度之和

    示例 :

    输入: words = ["cat","bt","hat","tree"], chars = "atach"
    输出: 6
    解释: 可以形成字符串 "cat" 和 "hat",所以答案是 3 + 3 = 6。

    输入: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
    输出: 10
    解释: 可以形成字符串 "hello" 和 "world",所以答案是 5 + 5 = 10。

    思路:

    • 简单的映射数组问题, 重点在于每次遍历, 需要创建一个临时计数的列表
    • 好久没写东西了, 最近能稍微写写

    代码:

        public List<Interval> merge(List<Interval> intervals) {
            if (intervals.size() == 0)
                return intervals;
            Collections.sort(intervals, new Comparator<Interval>() {
                public int compare(Interval a, Interval b) {
                    return a.start - b.start;
                }
            });
            Interval ii, jj;
        public int countCharacters(String[] words, String chars) {
            int res = 0;
            int[] tempChars = new int[26];
            int[] useCount;
            // 字母表映射数组
            for (int i = 0; i < chars.length(); i++) {
                tempChars[chars.charAt(i) - 'a']++;
            }
    
            int t;
            for (String word : words) {
                useCount = new int[26];
                res += word.length();
                for (int i = 0; i < word.length(); i++) {
                    t = word.charAt(i)- 'a';
                    useCount[t]++;
                    if (useCount[t] > tempChars[t]) {
                        res -= word.length();
                        break;
                    }
                }
            }
    
            return res;
        }
    

    分析:

    • 先遍历获取映射数组, 得到每个字母的使用次数
    • 遍历单词列表, 每个单词创建一个计数数组
    • 每个单词字母,计数数组统计出现次数, 并做判断: 若当前次数大于映射数组次数, 则返回(表示字母数目不足,无法创建单词)

    总结:

    • 非常简单的一道题, 效率排行榜的解题思路也大同小异

    相关文章

      网友评论

          本文标题:LeetCode 1160. 拼写单词 java

          本文链接:https://www.haomeiwen.com/subject/bpebictx.html