zoukankan      html  css  js  c++  java
  • 1160. 拼写单词

    地址:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters/

    <?php
    /**
    给你一份『词汇表』(字符串数组) 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。
     
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
     */
    class Solution {
    
        /**
         * @param String[] $words
         * @param String $chars
         * @return Integer
         */
        function countCharacters($words, $chars) {
            $hash = [];
    
            for ($i = 0,$length = strlen($chars);$i <$length;$i++){
                $hash[$chars[$i]] = ($hash[$chars[$i]] ?? 0) +1;
            }
            $num = 0;
            foreach ($words as $word){
                $tmp= $hash;
                for ($i = 0,$length = strlen($word);$i <$length;$i++){
                    if (!isset($tmp[$word[$i]]) || --$tmp[$word[$i]] <0){
                        continue 2;
                    }
                }
                $num+=$length;
            }
            return $num;
        }
    }
  • 相关阅读:
    mysql 启动不了,报错InnoDB相关
    vue 根据屏幕大小重新加载 echarts
    echarts 图例样式
    canvas 创建的图表,在移动端时,手指触碰,无法上下滑动页面
    uni-app 左上角返回按钮消失
    uni-app 缓存无法读取问题
    hbuider 运行 uni-app PC使用安卓模拟器接口请求错误
    wbstrom 使用git提交代码
    后端路由正常,但页面空白
    算法——RSA算法原理(转)
  • 原文地址:https://www.cnblogs.com/8013-cmf/p/13738411.html
Copyright © 2011-2022 走看看