LeetCode 1002. Find Common Characters

原题链接在这里:https://leetcode.com/problems/find-common-characters/

题目:

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. 1 <= A.length <= 100
  2. 1 <= A[i].length <= 100
  3. A[i][j] is a lowercase letter

题解:

Find the minimum of frequency for each lowercase char in each of string.

Time Complexity: O(n*m). n = A.length. m is average length of string in A.

Space: O(1).

AC Java:

 1 class Solution {
 2     public List<String> commonChars(String[] A) {
 3         List<String> res = new ArrayList<>();
 4         if(A == null || A.length == 0){
 5             return res;
 6         }
 7         
 8         int [] globalMap = new int[26];
 9         Arrays.fill(globalMap, Integer.MAX_VALUE);
10         for(String s : A){
11             int [] map = new int[26];
12             for(int i = 0; i<s.length(); i++){
13                 map[s.charAt(i) - 'a']++;
14             }
15             
16             for(int i = 0; i<26; i++){
17                 globalMap[i] = Math.min(globalMap[i], map[i]);
18             }
19         }
20         
21         for(int i = 0; i<26; i++){
22             for(int j = 0; j<globalMap[i]; j++){
23                 res.add(""+ (char)('a' + i));
24             }
25         }
26         
27         return res;
28     }
29 }

类似Intersection of Two Arrays II.

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12016026.html