zoukankan      html  css  js  c++  java
  • 1160. Find Words That Can Be Formed by Characters

    问题:

    给定一个字符串数组,和一个字典字符串,

    若字符串数组中的一个字符串中的所有字符,能够在字典字符串中一一对应找到(字典中每个字符只能用一次),则返回这个字符串的长度。

    最终返回满足条件的所有字符串长度之和。

    Example 1:
    Input: words = ["cat","bt","hat","tree"], chars = "atach"
    Output: 6
    Explanation: 
    The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.
    
    Example 2:
    Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
    Output: 10
    Explanation: 
    The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10. 
    
    Note:
    1 <= words.length <= 1000
    1 <= words[i].length, chars.length <= 100
    All strings contain lowercase English letters only.
    

      

    解法:

    用dict[26]保存字典字符串中各个字符出现的次数。

    再轮询字符串数组的每个字符串,

    在dict中查找对应的字符,找到一个dict[i]--

    因此,dict每次对比的时候需要copy一份dic用来临时判断,以不影响下一个字符串的判断。

    代码参考:

     1 class Solution {
     2 public:
     3     int getcount(string str, vector<int> dict){
     4         int cnt=0;
     5         vector<int> dic(dict);
     6         for(char s:str){
     7             if(dic[s-'a']<=0) return 0;
     8             dic[s-'a']--;
     9             cnt++;
    10         }
    11         return cnt;
    12     }
    13     int countCharacters(vector<string>& words, string chars) {
    14         vector<int> dict(26);
    15         int res=0;
    16         for(char c:chars){
    17             dict[c-'a']++;
    18         }
    19         for(string str:words){
    20             res+=getcount(str, dict);
    21         }
    22         return res;
    23     }
    24 };
  • 相关阅读:
    NConsoler 介绍
    HOWTO:批量删除存储过程和表
    HOWTO:使ASP.NET网站Forms验证可以指定多个登录页面
    [架构模式实践]如何不让第三方服务/组件的故障阻碍开发和测试进度
    GDI+学习笔记
    脚印: SD2C 2009 参会小记(非技术篇)
    Expression Web使用问题,相关资源及今日阅读
    HOWTO:FirePHP乱码问题解决
    [ECSHOP挖寶]用戶注銷過程
    励志好文
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/13124375.html
Copyright © 2011-2022 走看看