zoukankan      html  css  js  c++  java
  • 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/

  • 相关阅读:
    批处理
    使用T-SQL语句更新数据、删除
    使用T-SQL语句一次性插入另一张表的数据
    使用T-SQL语句插入数据
    CSS色调旋转滤镜
    初探Lerna
    基层管理人员的部分思考 --读《大秦帝国》有感
    (转)React学习笔记(干货满满)
    git常用命令(转)
    个人JS体系整理(三)
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/10508422.html
Copyright © 2011-2022 走看看