Leetcode: Find Common Characters

Find Common Characters



Similar Problems:


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

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


// Blog link: https://code.dennyzhang.com/find-common-characters
// Basic Ideas: array
// Complexity: Time O(n), Space O(1)
func commonChars(A []string) []string {
    l := make([]int, 26)
    for i:=0; i<26; i++ { l[i] = 100 }

    for _, s := range A {
        l2 := make([]int, 26)
        for _, ch := range s {
            i := byte(ch) - 'a'
            l2[i]++
        }
        for i:=0; i<26; i++ {
            if l2[i] < l[i] {
                l[i] = l2[i]
            }
        }
    }
    res := []string {}
    for i:=0; i<26; i++ {
        for j:=0; j<l[i]; j++ {
            res = append(res, string('a'+byte(i)))
        }
    }
    return res
}
linkedin
github
slack

Share It, If You Like It.

Leave a Reply

Your email address will not be published.