zoukankan      html  css  js  c++  java
  • [leetcode 周赛 150] 1160 拼写单词

    1160 Find Words That Can Be Formed by Characters 拼写单词

    描述

    给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串)chars
    假如你可以用chars中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。
    注意:每次拼写时,chars 中的每个字母都只能用一次。
    返回词汇表 words 中你掌握的所有单词的 长度之和

    • 示例 1:

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

    • 示例 2:

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

    • 提示:
      • 1 <= words.length <= 1000
      • 1 <= words[i].length, chars.length <= 100
      • 所有字符串中都仅包含小写英文字母

    思路

    • 读题

      • 拼写 使用字符串中的字符对应字母表中的字符 且每个字符只能使用一次
      • 条件 字符串都是小写英文字母
    • 这是一个一对多映射问题:

      1. 字符串中出现的字符 --> 字母表必然出现
      2. 字符在字母表出现次数大于等于在字符串出现次数
    • 可以使用数组来表示该映射关系
      一个数组elements, 记录字母表中各字母出现次数
      遍历字符串, 定位字符串字符在elements数组中出现次数减一
      但出现减一得负数则表示映射出错, 即无法完成拼写, 否则表示掌握该字符串

    代码实现

    class Solution {
        public int countCharacters(String[] words, String chars) {
            // chs 存储字母表中各字符出现次数
            int[] chs = new int[30];
            for (char c : chars.toCharArray()) {
                chs[c-'a']++;
            }
            
            // ans 当前所掌握字符串数量
            int ans = 0;
            // 遍历每个字符串
            for (int i = 0; i < words.length; i++) {
                // 当前处理字符串
                String cur = words[i];
                // 字母表原表克隆
                int[] curChs = chs.clone();
                // 当掌握该字符串 可以学到的字符数 没有掌握则为0
                int curAns = 0;
                for (char c : cur.toCharArray()) {
                    curAns++;
                    // 如果字母表中该字符不够组成字符串 则无法掌握该字符串
                    if (--curChs[c-'a'] < 0) {curAns = 0; break;}
                }
                ans += curAns;
            }
            
            return ans;
        }
    }
    
  • 相关阅读:
    zookeeper安装和使用
    一个最简单的Dubbo入门框架
    Dubbo Admin管理平台搭建
    Docker容器入门实践
    vue 项目安装 (入门)
    测试任何对象的某个特性是否存在 兼容js
    用户代理字符串检测呈现引擎、平台、Windows操作系统、移动设备和游戏系统 js
    React
    React (4) -- Conditional Rendering
    React (5) -- Lists and Keys
  • 原文地址:https://www.cnblogs.com/slowbirdoflsh/p/11383535.html
Copyright © 2011-2022 走看看