Given an array A
of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.
You may return the answer in any order.
Example 1:
Input: ["bella","label","roller"] Output: ["e","l","l"]
Example 2:
Input: ["cool","lock","cook"] Output: ["c","o"]
Note:
1 <= A.length <= 100
1 <= A[i].length <= 100
A[i][j]
is a lowercase letter
查找常用字符。
题意是给一个装了单词的数组,请求出这些单词里面共同的字母,以list形式输出。如果有多个相同的字母也需要多次输出。
思路是用hashmap记录input中第一个单词里面每个字母的出现次数,然后从第二个单词开始,也是去计算每个字母出现的次数,但是把某个字母在某个单词中出现的最少的次数加入结果集。举个例子,比如cool里面o出现了两次,但是在lock里面o只出现了一次,记录o的时候只记录最少的出现次数。最后遍历结果集里面每个单词,根据次数拼接成最后要输出的list。
时间O(n^2) - 每个单词 * 每个单词的长度
空间O(n)
1 class Solution { 2 public List<String> commonChars(String[] A) { 3 List<String> res = new ArrayList<>(); 4 int[] count = new int[26]; 5 Arrays.fill(count, Integer.MAX_VALUE); 6 for (String str : A) { 7 int[] cnt = new int[26]; 8 for (char c : str.toCharArray()) { 9 cnt[c - 'a']++; 10 } 11 for (int i = 0; i < 26; i++) { 12 count[i] = Math.min(count[i], cnt[i]); 13 } 14 } 15 16 for (int i = 0; i < 26; i++) { 17 while (count[i] > 0) { 18 res.add("" + (char) (i + 'a')); 19 count[i]--; 20 } 21 } 22 return res; 23 } 24 }
JavaScript实现
1 /** 2 * @param {string[]} A 3 * @return {string[]} 4 */ 5 var commonChars = function(A) { 6 let arrayList = []; 7 for (let str of A) { 8 let arr = new Array(26).fill(0); 9 for (let i = 0; i < str.length; i++) { 10 arr[str[i].charCodeAt() - 'a'.charCodeAt()]++; 11 } 12 arrayList.push(arr); 13 } 14 let res = []; 15 for (let i = 0; i < 26; i++) { 16 let min = 100; 17 for (let j = 0; j < arrayList.length; j++) { 18 if (arrayList[j][i] < min) { 19 min = arrayList[j][i]; 20 } 21 } 22 for (let k = 0; k < min; k++) { 23 res.push(String.fromCharCode(i + 'a'.charCodeAt())); 24 } 25 } 26 return res; 27 };