1.タイトルサイト
https://leetcode.com/problems/word-subsets/
2.タイトル説明
効果3.被験者
文字列配列A、文字列配列Bと一致与え、各文字列Bの発生数が<= A内の文字の数は、呼び出された場合、Bはサブセットです。
4.問題解決のアイデア
- 各列は最初のオリジナル文字の長さに対応する整数配列26に変換される整数配列インデックス、文字の元の配列の頻度を表す整数値を表します。
5. ACコード
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;
}
}