zoukankan      html  css  js  c++  java
  • (Good topic)哈希表:拼写单词 (3.17 leetcode每日打卡)

    给你一份『词汇表』(字符串数组) 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
     所有字符串中都仅包含小写英文字母
     
    思路:今天也是刚知道哈希表的应用,就是建立一个表,根据关键值(例如ASCLL码)直接访问数据元素,然后达到快速查表的目的。本题的思路就是先把字母表的个字母数记录,然后再根每个单词进行比较,字母出现一次就cp数组中就相应的那个字母个数减一,如果有个值小于0便跳出循环,再判断此时的words[i][j]是否为,不是就说明没有遍历到结尾,就不是一个完整的单词,继续循环,否则就长度加上此字符串长度。
     1 int countCharacters(char ** words, int wordsSize, char * chars)
     2 {
     3     int charsElemNum[26] = {0};
     4     int length = 0;
     5     int i, j;
     6 
     7     for (j = 0; chars[j]; j++) //对字母表中的个字母进行计数
     8     {
     9         charsElemNum[chars[j] - 97]++;
    10     }
    11     int cp[26];
    12 
    13     for (i = 0; i < wordsSize; i++)
    14     {
    15         for (j = 0; j < 26; j++)
    16         {
    17             cp[j] = charsElemNum[j];  //复制字母表中的元素
    18         }
    19         
    20         for (j = 0; words[i][j]; j++)
    21         {
    22             cp[words[i][j] - 97]--;
    23             if (cp[words[i][j] - 97] < 0)
    24             break;
    25         }
    26 
    27         if (words[i][j] != '')
    28             continue;
    29         else
    30             length += j;
    31     }
    32 
    33     return length;
    34 }
     
  • 相关阅读:
    python处理孤立的异常点
    使用redis实现程序或者服务的高可用
    redis报错: redis.exceptions.ResponseError: value is not an integer or out of range
    angular6 使用信息提示框toast
    浏览器中模仿跨域请求
    python aes_cbc加密
    openresty钉钉免密登陆
    openresty 钉钉签名计算
    ansible服务部署
    tornado 文件上传
  • 原文地址:https://www.cnblogs.com/ZhengLijie/p/12508751.html
Copyright © 2011-2022 走看看