栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

leetcode之字符串一: 查找共用字符

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

leetcode之字符串一: 查找共用字符

原题:

力扣https://leetcode-cn.com/problems/find-common-characters/submissions/

一、题目要求

给你一个字符串数组 words ,请你找出所有在 words 的每个字符串中都出现的共用字符( 包括重复字符),并以数组形式返回。你可以按 任意顺序 返回答案。
 

示例 1:

输入:words = ["bella","label","roller"]
输出:["e","l","l"]


示例 2:

输入:words = ["cool","lock","cook"]
输出:["c","o"]
 

提示:

1 <= words.length <= 1001 <= words[i].length <= 100words[i] 由小写英文字母组成

二、解题
package com.leetcode.string;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Solution11 {
    public static void main(String[] args) {
        String[] words = {"cool","lock","cook"};
        System.out.println(commonChars(words));
    }


    public static List commonChars(String[] words) {
        List> list = new ArrayList>();

        for (String word:words) {
            HashMap map = new HashMap();
            for (int i = 0; i < word.length(); i++) {
                char c = word.charAt(i);
                if (map.containsKey(c)) {
                    map.put(c, map.get(c) + 1);
                } else {
                    map.put(c, 1);
                }
            }
            list.add(map);
        }

        ArrayList l = new ArrayList();
        for (char c = 'a'; c <= 'z'; c++){
            int min = 0;        // 找最少出现的次数
            int count2 = 0;
            for (HashMap map:list) {
                Integer count = map.get(c);
                if (count == null) {
                    min = 0;
                    count2++;
                    break;
                }
                if (count2 == 0) {
                    min = count;
                }
                min = Math.min(min, count);
                count2++;
            }
            for (int i = 0; i < min; i++) {
                l.add(c + "");
            }
        }

        return l;
    }
}
三、运行结果

四、提交结果

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/720472.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号