当前位置: 代码迷 >> 综合 >> LeetCode 1170. 比较字符串最小字母出现频次
  详细解决方案

LeetCode 1170. 比较字符串最小字母出现频次

热度:71   发布时间:2024-02-23 23:42:56.0

目录结构

1.题目

2.题解


1.题目

我们来定义一个函数 f(s),其中传入参数 s 是一个非空字符串;该函数的功能是统计 s  中(按字典序比较)最小字母的出现频次。

例如,若 s = "dcce",那么 f(s) = 2,因为最小的字母是 "c",它出现了 2 次。

现在,给你两个字符串数组待查表 queries 和词汇表 words,请你返回一个整数数组 answer 作为答案,其中每个 answer[i] 是满足 f(queries[i]) < f(W) 的词的数目,W 是词汇表 words 中的词。

示例:

输入:queries = ["cbd"], words = ["zaaaz"]
输出:[1]
解释:查询 f("cbd") = 1,而 f("zaaaz") = 3 所以 f("cbd") < f("zaaaz")。输入:queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"]
输出:[1,2]
解释:第一个查询 f("bbb") < f("aaaa"),第二个查询 f("aaa") 和 f("aaaa") 都 > f("cc")。

提示:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/compare-strings-by-frequency-of-the-smallest-character
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2.题解

public class Solution1170 {@Testpublic void test1170() {String[] queries = {"bbb", "cc"}, words = {"a", "aa", "aaa", "aaaa"};System.out.println(Arrays.toString(numSmallerByFrequency(queries, words)));}public int[] numSmallerByFrequency(String[] queries, String[] words) {int[] fq = helper(queries);int[] fw = helper(words);int[] count = new int[11];for (int w : fw) {count[w]++;}for (int i = 1; i < 11; i++) {count[i] += count[i - 1];}int[] result = new int[fq.length];for (int i = 0; i < fq.length; i++) {result[i] = count[10] - count[fq[i]];}return result;}public int[] helper(String[] str) {int[] f = new int[str.length];for (int i = 0; i < str.length; i++) {int count = 0;char t = 'z' + 1;for (char c : str[i].toCharArray()) {if (t == c) {count++;} else if (c < t) {t = c;count = 1;}}f[i] = count;}return f;}
}