题目地址:
https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/
给定一个字符串,设一个函数
f
f
f,
f
(
s
)
f(s)
f(s)表示字符串
s
s
s中最小的字符的出现次数。再给定两个字符串数组queries
和words
,对每个queries里的字符串
q
q
q,求words里有多少个字符串
w
w
w满足
f
(
q
)
<
f
(
w
)
f(q)<f(w)
f(q)<f(w)。
思路是,可以先求出words里所有字符串的 f f f值,然后排个序得到数组freqOfWords,接着对queries里每个字符串 q q q求出 f ( q ) f(q) f(q)后,用二分法在freqOfWords里找第一个大于 f ( q ) f(q) f(q)的下标,这样就可以一下子求出有多少个数字比 f ( q ) f(q) f(q)大了。代码如下:
import java.util.Arrays;
public class Solution {
public int[] numSmallerByFrequency(String[] queries, String[] words) {
// 统计words里每个字符串的f值
int[] freqOfWords = new int[words.length];
for (int i = 0; i < words.length; i++) {
freqOfWords[i] = func(words[i]);
}
Arrays.sort(freqOfWords);
int[] res = new int[queries.length];
for (int i = 0; i < queries.length; i++) {
int freq = func(queries[i]);
res[i] = freqOfWords.length - binarySearch(freqOfWords, freq);
}
return res;
}
// 找到nums里第一个大于target的数字下标,如果不存在则返回nums的长度
private int binarySearch(int[] nums, int target) {
int l = 0, r = nums.length - 1;
while (l < r) {
int m = l + (r - l >> 1);
if (target >= nums[m]) {
l = m + 1;
} else {
r = m;
}
}
if (nums[l] > target) {
return l;
} else {
return l + 1;
}
}
// 求f(s)
private int func(String s) {
if (s.isEmpty()) {
return 0;
}
char ch = 'z' + 1;
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) < ch) {
ch = s.charAt(i);
count = 0;
} else if (s.charAt(i) == ch) {
count++;
}
}
return count;
}
}