LeetCode 1002. Find Common Character

原题

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

分析

题目的要求很简单,找出字符串集合中共有的字符,再者数据规模并不大,最多只有100个字符串,每个字符串里最多只有100个字符,因此解决这个问题的关键在于找一个合理的数据结构,用来存储这些公共的字符。

拍脑门解法

由于结果最多可以只有26字符,因此可以长度为26的数组来记录‘a’-'z’出现的次数,具体思路如下:

  1. 初始化count[26] = max_value;用来记录字符出现的次数
  2. 遍历A中的字符串
    • 初始化num[26] = 0
    • 对于每个字符串,用num数组记录该字符串中每个字符出现的次数,
    • 更新count数组值,count[i] = min(count[i], num[i]),这里得到的是到当前字符串位置,出现的每个字符的最小次数
  3. 遍历count数组
    • 如果count[i]>0,表示该字符为共有字符,且count[i]的值为出现的次数

作者@perfectpan

class Solution {
public:
    int cnt[26],num[26];
    vector<string> commonChars(vector<string>& A) {
        int i;
        for (i=0;i<26;++i) cnt[i]=100000;
        for (auto s:A){
            for (i=0;i<26;++i) num[i]=0;
            for (int i=0;i<(int)s.length();++i){
                num[s[i]-'a']++;
            }
            for (i=0;i<26;++i) cnt[i]=min(cnt[i],num[i]);
        }
        vector<string> vec;
        for (i=0;i<26;++i)if(cnt[i]>0){
            string s="";
            char ch='a'+i;
            s=s+ch;
            for (int j=0;j<cnt[i];++j){
                vec.push_back(s);
            }
        }
        return vec;
    }
};

Python四行解法

这里要提的一点是,在刷题的过程中,思路固然重要,但是合理的使用语言自身带有的数据结构库更重要(更何况一些题本来就用不着什么思路),有了这些我们便不用去费劲的造轮子,省时省力,可以节约时间来刷更多的题。

下面的解法用到了collections中的Counter类(其更多的用法可以参考博客http://www.pythoner.com/205.html)

这里只说下用到的两个知识点:

  1. Counter(str)得到str中的字符以及字符个数
>>> str = 'cool'
>>> c = Counter(str)
>>> c
Counter({'o': 2, 'c': 1, 'l': 1})
  1. 两个Counter之间可以使用&运算符,表示交集,并且计数取最小值(这不正是题目要求的么?)
>>> Counter('cool') & Counter('lock')
Counter({'c': 1, 'o': 1, 'l': 1})

作者@Hexadecimal

class Solution(object):
    def commonChars(self, A):
        """
        :type A: List[str]
        :rtype: List[str]
        """
        c = collections.Counter(A[0])
        for i in range(1, len(A)):
            c &= collections.Counter(A[i])
        return list(c.elements())
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章