LC.P1170[比较字符串最小字母出现频次]

方法一:后缀和

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public int[] numSmallerByFrequency(String[] queries, String[] words) {
int n = queries.length;
int[] cnt = new int[12];
for (String word : words) ++cnt[f(word)];
for (int i = 9; i >= 1; --i) {
cnt[i] += cnt[i + 1];
}
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
String s = queries[i];
ans[i] = cnt[f(s) + 1];
}
return ans;
}

private int f(String word) {
int cnt = 0;
char minC = 'z';
for (int i = 0; i < word.length(); ++i) {
char c = word.charAt(i);
if (c < minC) {
minC = c;
cnt = 1;
} else if (minC == c){
++cnt;
}
}
return cnt;
}
}
  • 时间复杂度:$O((n + m)p)$,其中$n = queries.length,m = words.length,p$为$words$中最长字符串的长度
  • 空间复杂度:$O(1)$