916. Word Subsets

作者: Rushia (みけねこ的鼻屎)   2022-07-30 19:05:07
https://leetcode.com/problems/word-subsets/
給予兩個字串陣列word1和word2
返回所有滿足word1之字串包含所有words2字串子集合的字串
class Solution {
public List<String> wordSubsets(String[] words, String[] patterns) {
List<String> res = new ArrayList<>();
int[] maxCount = new int[26];
for (String pattern : patterns) {
int[] patternCount = count(pattern);
for (int i = 0;i < 26;i++)
maxCount[i] = Math.max(maxCount[i], patternCount[i]);
}
for(String word : words) {
int[] wordCount = count(word);
if(match(wordCount, maxCount))
res.add(word);
}
return res;
}
private int[] count(String word) {
int[] res = new int[26];
for(char c : word.toCharArray())
res[c - 'a']++;
return res;
}
private boolean match(int[] a, int[] b) {
for(int i = 0;i < 26;i++)
if(a[i] < b[i]) return false;
return true;
}
}
先找出words2裡面的所有字串每個字母最多用幾個再和words1的字串match即可

Links booklink

Contact Us: admin [ a t ] ucptt.com