zoukankan      html  css  js  c++  java
  • leetcode 1002 查找常用字符串

    package com.example.lettcode.dailyexercises;
    
    import java.util.*;
    
    /**
     * @Class CommonChars
     * @Description 1002 查找常用字符串
     * @Author
     * @Date 2020/10/14
     **/
    public class CommonChars {
        // 只有小写字母,可以利用一个长度位26的数组
        public static List<String> commonChars(String[] A) {
            int[] minFreq = new int[26];
            // 用于保存常用的字符串
            Arrays.fill(minFreq, Integer.MAX_VALUE);
            List<String> ans = new ArrayList<>();
            for (int i = 0; i < A.length; i++) {
                int[] freq = new int[26];
                // 统计每个字符串中每个字符出现的次数
                for (int j = 0; j < A[i].length(); j++) {
                    ++freq[A[i].charAt(j) - 'a'];
                }
                // 到当前字符串为止,所能保留的常用字符串
                for (int j = 0; j < 26; j++) {
                    minFreq[j] = Math.min(minFreq[j], freq[j]);
                }
            }
    
            // 统计常用字符串
            for (int i = 0; i < 26; i++) {
                // 同一个字符可能会被重复使用多次
                for (int j = 0; j < minFreq[i]; j++) {
                    ans.add(String.valueOf((char) (i+ 'a')));
                }
            }
            return ans;
        }
    
    
        public static void main(String[] args) {
            String[] A = new String[]{"bella", "label", "roller"};
            List<String> ans = commonChars(A);
            System.out.println("CommonChars demo01 result:");
            for (String s : ans) {
                System.out.print(s + ',');
            }
            System.out.println();
            A = new String[]{"cool", "lock", "cook"};
            ans = commonChars(A);
            System.out.println("CommonChars demo02 result:");
            for (String s : ans) {
                System.out.print(s + ',');
            }
        }
    }
    
  • 相关阅读:
    【洛谷习题】公路修建
    priority_queue用法简记
    【洛谷习题】无线通讯网
    【SCOI2005】繁忙的都市
    第四周 3.20-3.26
    第三周 3.13-3.19
    第二周 3.6-3.12
    第一周 2.28-3.5
    第六周 2.21-2.27
    2018湘潭邀请赛 AFK题解 其他待补...
  • 原文地址:https://www.cnblogs.com/fyusac/p/13813562.html
Copyright © 2011-2022 走看看