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;
        }
    }
  • 相关阅读:
    app已损坏,打不开。你应该将它移到废纸篓。
    Mac/win eclipse genymotion 插件下载地址
    过大年
    error: L6235E: More than one section matches selector
    android socket 线程连接openwrt与arduino单片机串口双向通信
    PCB对应封装元件名称
    网页代码总结
    sql一个表中的数据插入到另外一个表中
    树莓派更换镜像源
    SQL 中的 AND OR
  • 原文地址:https://www.cnblogs.com/8013-cmf/p/13738411.html
Copyright © 2011-2022 走看看