Find Common Characters LT1002

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

Idea 1. build HashMap to count the occurence of each character, ('o' -> 2), loop each string in the array and build the array (used as HashMap), then scan the map, for each character, find out the minimul of the count and append the character as string to the array.

Time complexity: O(nm), n is the length of the array, m is the length of string, linear in terms of all charactes in the input array

Space complexity: O(26n)

 1 class Solution {
 2     public List<String> commonChars(String[] A) {
 3         int n = A.length;
 4        int[][] charCnt = new int[26][n];
 5         
 6         for(int i = 0; i < n; ++i) {
 7             for(int j = 0; j < A[i].length(); ++j) {
 8                 ++charCnt[A[i].charAt(j) - 'a'][i];
 9             }
10         }
11         
12         List<String> result = new ArrayList<>();
13         for(int i = 0; i < 26; ++i) {
14             int count = Integer.MAX_VALUE;
15             for(int j = 0; j < n; ++j) {
16                 count = Math.min(count, charCnt[i][j]);
17             }
18             while(count > 0) {
19                 result.add(Character.toString((char)('a' + i)));
20                 --count;
21             }
22         }
23         
24         return result;
25     }
26 }

Idea 1.a save space by storing the minimal counts on the way

Time compexity: O(n*m) linear

Space complexity: O(1)

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

猜你喜欢

转载自www.cnblogs.com/taste-it-own-it-love-it/p/10680946.html
今日推荐