zoukankan      html  css  js  c++  java
  • 统计一致字符串的数目

    给你一个由不同字符组成的字符串 allowed 和一个字符串数组 words 。如果一个字符串的每一个字符都在 allowed 中,就称这个字符串是 一致字符串 。

    请你返回 words 数组中 一致字符串 的数目。

    示例 1:

    输入:allowed = "ab", words = ["ad","bd","aaab","baa","badab"]
    输出:2
    解释:字符串 "aaab" 和 "baa" 都是一致字符串,因为它们只包含字符 'a' 和 'b' 。

    思路:

    1,将要匹配的字符串,字符都放到map中

    2,遍历字符数组,看匹配字符串是否都能在字串中存在

    代码:

    public int countConsistentStrings(String allowed, String[] words) {
    
            Map<Character,Character> characterMap = new HashMap<>();
            for (char c : allowed.toCharArray()) {
                characterMap.put(c,c);
            }
            int count = 0;
            for (String word : words) {
                boolean allSame = true;
                for (char c : word.toCharArray()) {
                    Character character = characterMap.get(c);
                    if(character == null){
                        allSame = false;
                    }
                }
                if (allSame){
                    count++;
                }
            }
            return count;
        }

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/count-the-number-of-consistent-strings
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  • 相关阅读:
    看代码所学1
    金额,重量,成绩不使用浮点数来表示,而使用整形
    安全风控的CAP原理和BASE思想
    Git操作
    项目上线规范以及一些词汇
    水滴筹面试
    Sping框架中的注解详解
    Restful技术
    @crossorigin注解跨域
    解决Ubuntu14.04下vi编辑器不能使用方向键和退格键问题
  • 原文地址:https://www.cnblogs.com/dongma/p/14218927.html
Copyright © 2011-2022 走看看