[LC] 1170. Compare Strings by Frequency of the Smallest Character

Let's define a function f(s) over a non-empty string s, which calculates the frequency of the smallest character in s. For example, if s = "dcce" then f(s) = 2 because the smallest character is "c" and its frequency is 2.

Now, given string arrays queries and words, return an integer array answer, where each answer[i] is the number of words such that f(queries[i]) < f(W), where W is a word in words.

 

Example 1:

Input: queries = ["cbd"], words = ["zaaaz"]
Output: [1]
Explanation: On the first query we have f("cbd") = 1, f("zaaaz") = 3 so f("cbd") < f("zaaaz").

class Solution {
    public int[] numSmallerByFrequency(String[] queries, String[] words) {
        int qNum = queries.length; 
        int wNum = words.length;
        int[] qArr = new int[qNum];
        int[] wArr = new int[wNum];
        for (int i = 0; i < qArr.length; i++) {
            qArr[i] = getSmallFreq(queries[i]);
        }
        for (int i = 0; i < wArr.length; i++) {
            wArr[i] = getSmallFreq(words[i]);
        }
        int[] res = new int[qNum];
        for (int i = 0; i < qNum; i++) {
            int tmp = 0;
            for (int wFreq: wArr) {
                if (qArr[i] < wFreq) {
                    tmp += 1;
                }
            }
            res[i] = tmp;
        } 
        return res;
    }
    
    private int getSmallFreq(String s) {
        int[] freqArr = new int[26];
        for (char c: s.toCharArray()) {
            freqArr[c - 'a'] += 1;
        }
        for (int i = 0; i < freqArr.length; i++) {
            if (freqArr[i] > 0) {
                return freqArr[i];
            }
        }
        return 0;
    }
}

 

posted @ 2020-02-12 10:33  xuan_abc  阅读(104)  评论(0编辑  收藏  举报