LeetCode.1170- string comparison of the frequency of occurrence of the smallest character (Compare Strings by Frequency of the Smallest Char)

This is the first Ogawa 412 update, the first 444 Pian original

Look problems and prepare

Introduced today is LeetCode algorithm in title Easy level of 263 questions (overall title number is 1170 ). A function is defined on a non-empty string S f(s), the function computes the sfrequency of occurrence of the smallest character. For example, if s ="dcce", then f(s)= 2, because of the smallest character "c", a frequency of 2.

Now, given an array of strings queriesand wordsreturns an array of integers answer,
where each answer[i]is such that f(queries[i]) < f(W)the number of words which Ware wordsin a word.

E.g:

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

Input: queries = [ "bbb", "cc"], words = [ "a", "aa", "aaa", "aaaa"]
Output: [1,2]
Description: In the first query, only f("bbb")<f("aaaa")so answer[0] = 1.
In the second f("cc")<f("aaa")query , f("cc")<f("aaaa")so answer[1] = 2.

Note :

  • 1 <= queries.length <= 2000
  • 1 <= words.length <= 2000
  • 1 <= queries[i].lengthwords[i].length <= 10
  • queries[i][j], words[i][j]English lowercase letters.

The first solution

Means title requirements words, find the minimum number of characters that appear less than queriesthe number of words in the character string the minimum number of occurrences, finally querieslength as intthe returned array.

Therefore, we can directly translate the title, use two layers of loop, the outer loop through queriesthe string to find the queries[i]number of occurrences of the smallest characters, then traversed wordsin a word, comparing the two characters minimum number of occurrences, if queriesthe relatively small , to count, after the inner loop, the count result is added to the answerarray, and finally returns.

public int[] numSmallerByFrequency(String[] queries, String[] words) {
    int len = queries.length, len2 = words.length;
    int[] result = new int[len];
    for (int i=0; i<len; i++) {
        int query = minFrequency(queries[i]);
        int count = 0;
        for (int j=0; j<len2; j++) {
            int word = minFrequency(words[j]);
            if (query < word) {
                count++;
            }
        }
        result[i] = count;
    }
    return result;
}

/**
 * 找到字符串中的最小字符的出现次数
 * @param s
 * @return
 */
public int minFrequency(String s) {
    int[] arr = new int[26];
    int count = 0;
    for (int i=0; i<s.length(); i++) {
        arr[s.charAt(i)-'a']++;
    }
    for (int j=0; j<26; j++) {
        if (arr[j] != 0) {
            count = arr[j];
            break;
        }
    }
    return count;
}


The second solution

For the first solution, the inner loop is calculated several times in the wordsminimum number of occurrences of a character in a word, we may be able to get out of the loop processing. The minimum first character of each word occurrences are calculated, stored in a length and wordsthe same intarray, in the inner loop, you can directly traverse the intarray, and each instead of all the re-count again.

public int[] numSmallerByFrequency2(String[] queries, String[] words) {
    int len = queries.length, len2 = words.length;
    int[] wordFreq = new int[len2];
    for (int j=0; j<len2; j++) {
        wordFreq[j] = minFrequency(words[j]);
    }
    int[] result = new int[len];
    for (int i=0; i<len; i++) {
        int query = minFrequency(queries[i]);
        int count = 0;
        for (int j=0; j<len2; j++) {
            if (query < wordFreq[j]) {
                count++;
            }
        }
        result[i] = count;
    }
    return result;
}

/**
 * 找到字符串中的最小字符的出现次数
 * @param s
 * @return
 */
public int minFrequency(String s) {
    int[] arr = new int[26];
    int count = 0;
    for (int i=0; i<s.length(); i++) {
        arr[s.charAt(i)-'a']++;
    }
    for (int j=0; j<26; j++) {
        if (arr[j] != 0) {
            count = arr[j];
            break;
        }
    }
    return count;
}


A third solution

For both the previous solution, we can then simplify it down? For example, the two become one loop cycle? To change one cycle, then calculate querieswhen the string, you need time to get the results, do not use cycle, that is the same as the value in the array.

The second example we first observed next. In processed wordswhen the word will get an array wordFreq, on this basis to do under the change, do the counting process, the index number of the array as a new character appears minimal, the cumulative number again, you get the following four:

count[4] = 1; //"aaaa"代表的单词
count[3] = 1; //"aaa"代表的单词
count[2] = 1; //"aa"代表的单词
count[1] = 1; //"a"代表的单词

Come under observation queriesarrays, strings "bbb"and "cc"go and wordscomparison of words, will have the following rules:

大于"bbb"的有1位,记为arr[3] = 1
大于"cc"的有2位,记为arr[2] = 2

If you then write down:

大于1的有3位,arr[1] = 3
大于0的有4位,arr[0] = 4

We found that, with queriesthe smallest number of occurrences of the string of characters as an index of arrthe array, in fact, above the countreverse element of the array cumulative sum of:

arr[3] = count[4] = 1;
arr[2] = arr[3] + count[3] = 1+1 = 2

which is:

arr[i-1] = arr[i]+count[i];

After analyzing the principle out of which the rest is to write the code, and this solution is much faster than on the previous two solutions speed.

public int[] numSmallerByFrequency3(String[] queries, String[] words) {
    int len = queries.length;
    int[] wordFreq = new int[11];
    for (String word : words) {
        wordFreq[minFrequency(word)]++;
    }
    int[] sum = new int[11];
    for (int i=sum.length-1; i>0; i--) {
        sum[i-1] = sum[i]+wordFreq[i];
    }
    int[] result = new int[len];
    for (int i=0; i<len; i++) {
        result[i] = sum[minFrequency(queries[i])];
    }
    return result;
}

/**
 * 找到字符串中的最小字符的出现次数
 * @param s
 * @return
 */
public int minFrequency(String s) {
    int[] arr = new int[26];
    int count = 0;
    for (int i=0; i<s.length(); i++) {
        arr[s.charAt(i)-'a']++;
    }
    for (int j=0; j<26; j++) {
        if (arr[j] != 0) {
            count = arr[j];
            break;
        }
    }
    return count;
}


summary

Thematic algorithm has now updated LeetCode algorithm of feature articles 269 + articles, public Number dialog box reply [ data structures and algorithms ], [ algorithm ], [ data structures either] in a keyword, to obtain a series of articles collection.

That's all, if you have any good solution ideas, suggestions or other issues, you can exchange comments below, thumbs up, message forwarding and support is the greatest reward for me!

Guess you like

Origin www.cnblogs.com/xiaochuan94/p/11570371.html