Leetcode 1002. Find Common Characters, Java 解法

直流电机双闭环调速系统MATLAB仿真 Chopper-Fed DC Motor Drive This example shows a Chopper-Fed DC Motor Drive. Description The DC motor is fed by the DC source through a chopper which consists of GTO thyristor and free-wheeling diode ... 阅读详情

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

Approach #1 dictionary

class Solution {
    public List<String> commonChars(String[] A) {
        List<String> ans = new ArrayList<>();
    
        // Common characters dictionary
        int[] dict = new int[26];
        for (int j = 0; j < A[0].length(); j++) {
            dict[A[0].charAt(j) - 'a']++;
        }
    
        for (int i = 1; i < A.length; i++) {
            
            // Dictionary of the current word
            int[] curr = new int[26];
            for (int j = 0; j < A[i].length(); j++) {
                curr[A[i].charAt(j) - 'a']++;
            }
            
            // Update the common dictionary
            for (int j = 0; j < 26; j++) {
                if (curr[j] < dict[j]) 
                    dict[j] = curr[j];
            }
        }
        
        for (int i = 0; i < 26; i++) {
            for (int j = 0; j < dict[i]; j++) {
                ans.add(Character.toString((char) ('a' + i)));
            }
        }
        return ans;
    }
}

先把所有String []A 里出现过的字母加到公共字典里,然后对String[] A里每一个String word, 用一个字典储存其每个字母出现过的次数,然后更新公共的字典。

这样一来,公共字典里储存的,都是每个word里字母至少出现的次数,如果没在其他word出现过,会被设为0.

Time: O(n), where n is the total number of characters in A;
extra space: O(1), excludes output/return space.

 

Approach #2  与上一方法思想类似,代码更简洁

    public List<String> commonChars(String[] A) {
        List<String> ans = new ArrayList<>();
        int[] count = new int[26]; 
        Arrays.fill(count, Integer.MAX_VALUE);
        for (String str : A) {
            int[] cnt = new int[26];
            for (int i = 0; i < str.length(); ++i) { ++cnt[str.charAt(i) - 'a']; } // count each char's frequency in string str.
            for (int i = 0; i < 26; ++i) { count[i] = Math.min(cnt[i], count[i]); } // update minimum frequency.
        }
        for (char c = 'a'; c <= 'z'; ++c) {
            while (count[c - 'a']-- > 0) { ans.add("" + c); }
        }
        return ans;
    }

Time: O(n), where n is the total number of characters in A;
extra space: O(1), excludes output/return space.

Q: What does ++cnt[c - 'a']; mean?

A:count the frequency of chars in String str.

c : cnt[c - 'a']

'a': cnt['a' - 'a'] = cnt[0]
'b': cnt['b' - 'a'] = cnt[1]
'c': cnt['c' - 'a'] = cnt[2]
...
'z': cnt['z' - 'a'] = cnt[25]

if char c represents 'x', then cnt[c - 'a'] = cnt[23]. That is, when encountering char 'x', we increase cnt[23] by 1.

Therefore, after traversal of all chars in String str, we have the frequency (number of occurrence) of each char in cnt.

西门子TP900精智系列触摸屏和三菱Q系列PLC以太网通信的组态步骤 阅读详情

相关推荐

告别反复格式化!用Ventoy制作2025年终极启动盘,Windows/Linux/macOS一网打尽

本文详细介绍了如何使用Ventoy制作2025年终极多系统启动盘,彻底告别反复格式化U盘的烦恼。Ventoy通过创新的引导加载器架构,允许用户在一个U盘内同时存放并直接启动Windows、Linux、macOS等多种系统镜像和WePE等维护工具,实现真正的非破坏性管理和极高的U盘利用率。文章涵盖从安装配置、镜像库构建到安全启动设置等全流程实战指南。

weixin_29280219的博客 241

【LeetCode】1002. 查找常用字符(Java)

给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。 你可以按任意顺序返回答案。 提示: 1 <= A.length <= 100 1 <= A[i].length <= 100 A[i][j] 是小写字母 class Solution { public List<String> commonChars(St

小楊同学的笔记本 269

Python爬虫实战:5分钟搞定东方财富网股票数据抓取(附完整代码)

本文详细介绍了如何使用Python爬虫快速抓取东方财富网的股票数据,包括环境配置、API分析、核心代码实现及优化技巧。通过简单的requests和pandas库,5分钟内即可获取高质量股票数据,适合量化交易和数据分析初学者。

weixin_29040367的博客 1183

[Leetcode][第1002题][JAVA][查找常用字符][计数][HashMap]

【问题描述】[简单] 【解答思路】 计数法 1. minfreq存放最终重复字母的个数 freq存放每次遍历字符串的字母个数 2. minfreq初始化最大值,每遍历一个字符串后,比较minfreq[i]、freq[i]的大小,minfreq[i]更新为两者的最小值。 3. 根据minfreq,输出答案 时间复杂度:O(N^2) 空间复杂度:O(N) class Solution { public List<String> commonChars(String[] A) {

dadongwudi的博客 271

集成电路模拟版图入门-版图基础学习笔记(四)

第三部分:版图的准备 2. 设计规则 3) Design Rule 2. 设计规则 4) 规则定义 4.1 NW(N WELL) 2. 设计规则 4) 规则定义 4.1 NW(N WELL) 2. 设计规则 4) 规则定义 4.2 PO(Poly) 2. 设计规则 4) 规则定义 4.3 M1(Metal1) 2. 设计规则 4) 规则定义 4.4 VIA 3. DRC文件 3.1 DRC:Design Rule Check,设计规则检查。 3.2 DRC程序了解有关

weixin_52955333的博客 6734

六自由度机器人(机械臂)运动学建模及运动规划系列(四)——轨迹规划

本篇介绍了六轴机器人关节空间以及笛卡尔空间轨迹规划的简单方法,并给出了一种几何解法,以简化规划过程,并提供了简单的Matlab轨迹规划函数介绍。

weixin_47849087的博客 5万+

leetcode -1002 -查找常用字符 -java版

文章目录题目代码 题目 给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。 你可以按任意顺序返回答案。 示例 1: 输入:[“bella”,“label”,“roller”] 输出:[“e”,“l”,“l”] 示例 2: 输入:[“cool”,...

lingle1的博客 498

[机器学习-回归实例] 李宏毅机器学习作业一:PM2.5 预测实例

[机器学习-回归实例] 李宏毅机器学习作业一:PM2.5 预测实例 简介   这是一个回归预测的实例,数据集来自李宏毅的《机器学习》课程的第一次作业,可以用来训练一个线性回归模型或者其他的回归模型,动手实践学习到的理论知识,在实践中去发现问题。这篇文章主要包括数据集的解释、数据的预处理过程及线性回归模型的代码实现这三个部分。由于这个数据集并不能直接使用,还需进行一些重构,为了对初学者更友好一些,我会提供重构完的可以读取后就直接使用的数据集,我也会提供 Matlab\rm MatlabMatlab 可直接使用

qq_27309515的博客 3574

力扣1002.查找常用字符

1、这题一开始我把所有字母一起map导致忽略了有些单词有多个有些没有。。 这是一道简单的题26个字母记录,在每个单词中出现的最小次数,最后放到容器里面输出 知识点1:char转化为string string(const char *s); //用c字符串s初始化 string(int n,char c); //用n个字符c初始化 strings(1,i+'a');//char->string class Solution { public: vec...

小吕的博客 223

Python画好看的雷达图,全网开源代码最好看的

【代码】Python画好看的雷达图,全网开源代码最好看的。

大模型天花板 2280

推荐系统在音乐领域的实践:网易云音乐推荐算法解析

你是否有过这样的经历?打开网易云音乐,“私人FM”里总能推到你想听的歌;“每日推荐”的歌单,往往藏着你没听过但一入耳就爱上的曲目。这些“懂你”的推荐背后,是一套复杂却精密的推荐系统在运转。问题陈述:音乐推荐的难点远超一般商品——音乐是高度主观的艺术,用户兴趣易随心情、场景变化;小众音乐的“长尾效应”显著,如何让冷门好歌被发现?传统协同过滤依赖历史行为,面对新用户/新歌曲的“冷启动”问题束手无策;而单纯的内容推荐又难以捕捉用户的隐性兴趣。核心方案:网易云音乐采用“混合推荐策略”——融合协同过滤(CF)

AI天才研究院 2086

Java/1002. Find Common Characters 查找常用字符

题目 代码部分(4ms 99.26%) class Solution { public List<String> commonChars(String[] A) { List<String> res = new ArrayList(); if(A == null || A.length == 0) re...

qq_38959715的博客 1499

执行HDevelop项目

这一节,我们讲述的是如何用HDevEngine加载和执行一个HDevelop项目。代码部分来源于示例程序exec_program(源文件exec_program.cpp),检测塑料零件边界上的毛刺。1.Step 1:初始化首先,我们包含HALCON/C++和HDevEngine头文件以及命名空间。注意到在这个示例程序中,HDevEngine头文件已经包含在my_hdevoperatorimpl中,所

Z's Palace 2994

1002. Find Common Characters

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 ...

maomao_dreamhigh的博客 369

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

LeetCode.1002-寻找共有字符(Find Common Characters)

这是悦乐书的第375次更新,第402篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第236题(顺位题号是1002)。给定仅由小写字母组成的字符串A,返回列表中所有字符串都有显示的字符的列表(包括重复字符)。例如,如果一个字符在所有字符串中出现3次但不是4次,则需要在最终答案中包含该字符三次。 你可以按任何顺序返回答案。例如: 输入:["bella","la...

weixin_30493321的博客 84

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

LeetCode-Find Common Characters

LeetCode Java Find Common Characters

坟头草一米七五 282

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

Find Common Characters

Given an arrayAof 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 ...

m0_37889928的博客 404

1002. Find Common Characters查找常用字符

参考:https://leetcode.com/problems/find-common-characters/discuss/247573/C%2B%2B-O(n)-or-O(1)-two-vectors 地址:https://leetcode.com/problems/find-common-characters/ vector初始化:vector<int> a(7,3) ...

weixin_33714884的博客 174

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

1002.Find Common Characters(查找常用字符 )DescriptionDifficulty: easyExample 1:Example 2:Note:分析参考代码 Description Given an array A of strings made only from lowercase letters, return a list of all characters...

redtongue的博客 487

【字符串】C040_LC_查找常用字符(求交集)

一、题目描述 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 o...

无敌兔0x01 524

leetcode刷题记录-1002查找常用字符[java,数组]*

题目 给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。 你可以按任意顺序返回答案。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/find-common-characters 著作权归...

AG9GgG的博客 358

Leetcode 1002:查找常用字符(超详细的解法!!!)

给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。 你可以按任意顺序返回答案。 示例 1: 输入:["bella","label","roller"] 输出:["e","l","l"] 示例 2: 输入:["cool&quo

coordinate的博客 2340

leetcode1002查找常用字符(Java)(hashmap)

class Solution { public List<String> commonChars(String[] A) { Map<Character,Integer> map=new HashMap<>(); for(char c:A[0].toCharArray()){ map.put(...

qq_35706707的博客 404

【Leetcode】1002. Find Common Characters

class Solution1(object): """ use Counter's intersection and elements """ def commonChars(self, A): if len(A) == 0: return [] from collections import Counter C ...

很吵请安静 384

LeetCode算法题:查找常用字符commonChars

给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。 你可以按任意顺序返回答案。 示例 1: 输入:["bella","label","roller"] 输出:["e","l","l"] 示例 2: 输入:["cool","lock...

Mike的博客 256

城市探索新视角:用轮滑工具丈量个人生活圈与通勤半径

在城市交通规划与个人出行领域,通勤半径和生活圈是衡量城市可达性与生活质量的核心概念。其原理基于时空地理学,通过人力或辅助动力交通工具,在可接受的时间与体力成本内,界定个体的日常活动范围。这一实践不仅有助于优化个人出行效率,更能提升对城市空间的感知与利用。在技术价值上,它融合了路线规划、运动数据记录与地理信息标注,是城市探索与微出行的具体应用。应用场景广泛覆盖日常通勤替代、社区生活便利性评估、休闲健身路线开发及城市微旅行。本文聚焦于通过自行车、电动滑板车等轮滑工具,系统性地执行此类探索,涉及装备选型、安全准则

weixin_30522095的博客 355
上一篇: Leetcode 999. Available Captures for Rook , Java解法。
下一篇: Leetcode 867. Transpose Matrix, Java解法
YuanTheCoder
博客等级 码龄9年 2粉丝 34原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值