Find Common Characters
This problem was marked as "easy" on leetcode, here it is: https://leetcode.com/problems/find-common-characters/
This is somehow a set-problem: keep looking for the intersection of sets, where the set is the characters in each string. I use few (three) hash tables to "store" the sets, keeping the primary one which will be used at the end as the result. Code is down below, cheers, ACC.
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
This is somehow a set-problem: keep looking for the intersection of sets, where the set is the characters in each string. I use few (three) hash tables to "store" the sets, keeping the primary one which will be used at the end as the result. Code is down below, cheers, ACC.
public class Solution { public IListCommonChars(string[] A) { if (A == null || A.Length == 0) return new List (); Hashtable primary = new Hashtable(); AddToHash(A[0], ref primary); for (int i = 1; i < A.Length; i++) { Hashtable secondary = new Hashtable(); AddToHash(A[i], ref secondary); Hashtable temp = new Hashtable(); foreach (char c in secondary.Keys) { if (primary.ContainsKey(c)) { temp.Add(c, Math.Min((int)primary[c], (int)secondary[c])); } } primary = (Hashtable)temp.Clone(); } List retVal = new List (); foreach (char c in primary.Keys) { int count = (int)primary[c]; for (int i = 0; i < count; i++) { retVal.Add(c.ToString()); } } return retVal; } private void AddToHash(string str, ref Hashtable hash) { for (int i = 0; i < str.Length; i++) { if (!hash.ContainsKey(str[i])) { hash.Add(str[i], 0); } hash[str[i]] = (int)hash[str[i]] + 1; } } }
Comments
Post a Comment