LeetCode 1002. Find Common Characters (查找常用字符)

题目标签:Array, Hash Table

  题目给了我们一个string array A,让我们找到common characters。

  建立一个26 size 的int common array,作为common characters 的出现次数。

  然后遍历每一个 string, 都建立一个 int[26] 的 temp array,来数每个char 出现的次数,当完成了这个str 之后,

  把这个temp array 更新到 common 里面去,这里要挑最小的值存入。当完成所有string 之后,common array 里面剩下的,

  就是我们要找的常用字符。

  具体看code。

Java Solution:

Runtime beats 58.42% 

完成日期:03/08/2019

关键点:对于每一个新的string,把common array 里面的次数进行更新,取最小的次数,排除不是 common 的 字符。

class Solution 
{
    public List<String> commonChars(String[] A) 
    {
        List<String> result = new ArrayList<>();
        int [] commonCharsCount = new int[26];
        Arrays.fill(commonCharsCount, Integer.MAX_VALUE);
        
        // iterate each string in A
        for(String str : A)
        {
            int [] tempCharsCount = new int[26];
            
            // count char for this string
            for(char c : str.toCharArray())
                tempCharsCount[c - 'a']++;
            
            // update the commonCharsCount
            for(int i=0; i<commonCharsCount.length; i++)
                commonCharsCount[i] = Math.min(commonCharsCount[i], tempCharsCount[i]);
        }
        
        // iterate commonCharsCount to add each char
        for(int i=0; i<commonCharsCount.length; i++)
        {
            while(commonCharsCount[i] > 0)
            {
                result.add("" + (char)('a' + i));
                commonCharsCount[i]--;
            }
        }
        
        return result;
    }
    

}

参考资料:https://leetcode.com/problems/find-common-characters/discuss/?currentPage=1&orderBy=recent_activity&query=

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

原文地址:https://www.cnblogs.com/jimmycheng/p/10508422.html