leetcode-Algorithms-1684 |统计一致字符串的数目

原题

在这里插入图片描述

思路

set去重

代码

刚开始审错题了,以为是判断allowed是否在数组在的元素有连续,提交后才发现自己写错,但是又不想删除写的。

package leetcode.Algorithms;


import java.util.HashSet;

public class Solution1684 {
    
    
    public static void main(String[] args) {
    
    
        String[] s = {
    
    "ad", "bd", "aaab", "baa", "badab"};

        System.out.println(countConsistentStrings("ab", s));
    }

    public static int countConsistentStrings(String allowed, String[] words) {
    
    
        if (allowed == null || allowed == "" || words == null) {
    
    
            return 0;
        }
        int count = 0;
        HashSet<Character> set = new HashSet<Character>();
        for (int i = 0; i < allowed.length(); i++) {
    
    
            set.add(allowed.charAt(i));
        }
        for (String word : words) {
    
    
            boolean f = false;
            for (int i = 0; i < word.length(); i++) {
    
    
                if (!set.contains(word.charAt(i))) {
    
    
                    f = true;
                    break;
                }
            }
            if (!f) {
    
    
                count++;
            }
        }

        return count;
    }

    public static int countConsistentStrings_errot(String allowed, String[] words) {
    
    
        if (allowed == null || allowed == "" || words == null) {
    
    
            return 0;
        }
        int allowedlength = allowed.length();
        int count = 0;
        for (int i = 0; i < words.length; i++) {
    
    
            if (words[i].length() >= allowedlength) {
    
    
                int t = words[i].length() - allowedlength + 1;
                for (int j = 0; j < t; j++) {
    
    
                    String sub = words[i].substring(j, allowedlength+j);
                    if (sub.endsWith(allowed) ) {
    
    
                        count++;
                    }
                }
            }
        }
        return count;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38173650/article/details/114935020