# LeetCode.1170-比较字符串中最小字符的出现频率(Compare Strings by Frequency of the Smallest Char)

## 看题和准备

• 1 <= `queries.length` <= 2000
• 1 <= `words.length` <= 2000
• 1 <= `queries[i].length``words[i].length` <= 10
• `queries[i][j]``words[i][j]`是英文小写字母。

## 第一种解法

``````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;
}
``````

## 第二种解法

``````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;
}
``````

## 第三种解法

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

``````大于"bbb"的有1位，记为arr[3] = 1

``````

``````大于1的有3位，arr[1] = 3

``````

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

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

``````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;
}
``````