1. 程式人生 > 實用技巧 >leetcode 1002 查詢常用字串

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 + ',');
        }
    }
}