comments | difficulty | edit_url | rating | source | tags | |||
---|---|---|---|---|---|---|---|---|
true |
简单 |
1279 |
第 126 场周赛 Q1 |
|
给你一个字符串数组 words
,请你找出所有在 words
的每个字符串中都出现的共用字符(包括重复字符),并以数组形式返回。你可以按 任意顺序 返回答案。
示例 1:
输入:words = ["bella","label","roller"] 输出:["e","l","l"]
示例 2:
输入:words = ["cool","lock","cook"] 输出:["c","o"]
提示:
1 <= words.length <= 100
1 <= words[i].length <= 100
words[i]
由小写英文字母组成
我们用一个长度为
时间复杂度
class Solution:
def commonChars(self, words: List[str]) -> List[str]:
cnt = Counter(words[0])
for w in words:
t = Counter(w)
for c in cnt:
cnt[c] = min(cnt[c], t[c])
return list(cnt.elements())
class Solution {
public List<String> commonChars(String[] words) {
int[] cnt = new int[26];
Arrays.fill(cnt, 20000);
for (var w : words) {
int[] t = new int[26];
for (int i = 0; i < w.length(); ++i) {
++t[w.charAt(i) - 'a'];
}
for (int i = 0; i < 26; ++i) {
cnt[i] = Math.min(cnt[i], t[i]);
}
}
List<String> ans = new ArrayList<>();
for (int i = 0; i < 26; ++i) {
ans.addAll(Collections.nCopies(cnt[i], String.valueOf((char) ('a' + i))));
}
return ans;
}
}
class Solution {
public:
vector<string> commonChars(vector<string>& words) {
vector<int> cnt(26, 20000);
for (const auto& w : words) {
vector<int> t(26, 0);
for (char c : w) {
++t[c - 'a'];
}
for (int i = 0; i < 26; ++i) {
cnt[i] = min(cnt[i], t[i]);
}
}
vector<string> ans;
for (int i = 0; i < 26; ++i) {
for (int j = 0; j < cnt[i]; ++j) {
ans.push_back(string(1, 'a' + i));
}
}
return ans;
}
};
func commonChars(words []string) (ans []string) {
cnt := make([]int, 26)
for i := range cnt {
cnt[i] = 20000
}
for _, w := range words {
t := make([]int, 26)
for _, c := range w {
t[c-'a']++
}
for i := 0; i < 26; i++ {
cnt[i] = min(cnt[i], t[i])
}
}
for i := 0; i < 26; i++ {
for j := 0; j < cnt[i]; j++ {
ans = append(ans, string('a'+rune(i)))
}
}
return ans
}
function commonChars(words: string[]): string[] {
const cnt = Array(26).fill(20000);
const aCode = 'a'.charCodeAt(0);
for (const w of words) {
const t = Array(26).fill(0);
for (const c of w) {
t[c.charCodeAt(0) - aCode]++;
}
for (let i = 0; i < 26; i++) {
cnt[i] = Math.min(cnt[i], t[i]);
}
}
const ans: string[] = [];
for (let i = 0; i < 26; i++) {
cnt[i] && ans.push(...String.fromCharCode(i + aCode).repeat(cnt[i]));
}
return ans;
}