[String-mdium] 916. Word Subsets If the number of occurrences of each character string b are smaller than or equal to the number of occurrences of a character, b is called a subset.

1. The title site

https://leetcode.com/problems/word-subsets/

2. Title Description

Here Insert Picture Description

3. subject to the effect

Given a string array A, and matching a string array B, if the number of occurrences of each character string B are <= the number of the character in A, called A, B is a subset.

4. Problem-solving ideas

  • Each string is first converted to the integer array 26 corresponding to the length of the original characters represent integer array index, an integer value representing the frequency of the original array of characters.

5. AC Code

class Solution {
    public List<String> wordSubsets(String[] A, String[] B) {
        List<String> ret = new ArrayList<String>();
        int b[] = new int[26];
        for(String s: B) {
            b = combine(s, b);  // 返回给定的B中的所有元素,每个元素都要是最大的个数。
        }
        for(String a: A) {
            if(contain(a,b)) ret.add(a);
        }
        return ret;
    }

    private boolean contain(String a, int[] b) {  // 判断这个字符串是否包含B中所有的字符
        int[] temp = new int[26];
        for(char c: a.toCharArray())  // 将给定的字符串转换为对应的整型26位数组
            temp[c - 'a'] ++;
        for(int i = 0; i < 26; i ++) {
            if(temp[i] < b[i])
                return false;
        }
        return true;
    }

    private int[] combine(String s, int[] b) {
        int[] temp = new int[26];
        for(char c: s.toCharArray()) {
            temp[c - 'a'] ++;  // 将字符作为下标,出现的频率作为值存储到整型数组中
        }
        for(int i = 0; i < 26; i++) {
            b[i] = Math.max(b[i],temp[i]);  // 每一位应该存储的是出现的最多的频率
        }
        return b;
    }
}

Guess you like

Origin blog.csdn.net/xiaojie_570/article/details/92602251