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 }

AC C++:

 1 class Solution {
 2 public:
 3     vector<string> commonChars(vector<string>& words) {
 4         vector<string> res;
 5         vector<int> global_map(26, INT_MAX);
 6         for(auto& word : words){
 7             vector<int> map(26, 0);
 8             for(auto& c : word){
 9                 map[c - 'a']++;
10             }
11 
12             for(int i = 0; i < 26; i++){
13                 global_map[i] = min(global_map[i], map[i]);
14             }
15         }
16 
17         for(int i = 0; i < 26; i++){
18             for(int j = 0; j < global_map[i]; j++){
19                 res.push_back(string(1, 'a' + i));
20             }
21         }      
22 
23         return res;
24     }
25 };

类似Intersection of Two Arrays II.

posted @ 2019-12-10 13:12  Dylan_Java_NYC  阅读(332)  评论(0编辑  收藏  举报