描述
给定一个字符串,我们想知道满足以下两个条件的子串最多出现了多少次:
写一个函数 getMaxOccurrences ,其返回满足条件的子串最多出现次数。
2≤n≤1052≤n≤1052≤minLength≤maxLength≤262≤minLength≤maxLength≤26maxLength nmaxLength n2≤maxUnique≤262≤maxUnique≤26ss仅包含小写字母在线评测地址:领扣题库官网
样例1 s = "abcde" minLength = 2 maxLength = 5 maxUnique = 3 符合条件的子串有 ab, bc, cd, de, abc, bcd, cde 。每一个子串只出现了一次,因此答案是1。
解题思路
我们可以使用滑动窗口的做法。显然,题目中的maxLengthmaxLength是没有用的,因此我们只需要以枚举所有minLengthminLength长的子串,判断其是否符合maxUniquemaxUnique的条件。如果符合,进行计数即可。
源代码
public class Solution { * @param s: string s * @param minLength: min length for the substring * @param maxLength: max length for the substring * @param maxUnique: max unique letter allowed in the substring * @return: the max occurrences of substring public int getMaxOccurrences(String s, int minLength, int maxLength, int maxUnique) { // write your code here int[] letterCount = new int[26]; /*count letter*/ char[] strs = s.toCharArray(); Map String,Integer stringCount = new HashMap (); /*count specific string satisfy requirement.*/ int start = 0, end = start + minLength - 1, letterTotal = 0, ans = 0; /*letterTotal stores current total number of distinct letter. */ /*deal with the first string with minLength. */ for(int i = start; i = end; i++){ if(letterCount[strs[i] - 'a'] == 0) letterTotal++; letterCount[strs[i] - 'a']++; if(letterTotal = maxUnique){ stringCount.put(s.substring(start, end + 1), 1); ans = 1; /*slide in one letter, slide out one letter, and check if the substring in the sliding window satisfy the requirement. */ end++; while(end s.length()){ if(letterCount[strs[end] - 'a']++ == 0) letterTotal++; if(letterCount[strs[start] - 'a']-- == 1) letterTotal--; start++; if(letterTotal = maxUnique){ String curStr = s.substring(start, end + 1); stringCount.put(curStr, stringCount.getOrDefault(curStr, 0) + 1); ans = Math.max(ans, stringCount.get(curStr)); end++; return ans; }
更多题解参考:九章官网solution
作为新一代微服务架构体系, Service Mesh 技术有效地解决了 Spring Cloud 微服...
虚拟主机 根目录是什么?虚拟主机根目录是指虚拟主机的一级目录文件夹,在搭 建...
目标 在仿真理论中,生成随机变量是最重要的构建块之一,而这些随机变量大多是由...
一、你的App也经常作妖么? 曾经听一位金融类的top sales吐槽自家App稳定性的问...
帮助用户完成云服务器备份任务的创建,快速完成服务器数据保护。 前提条件 启用...
在数据分析工作中,细分思维的重要性,我认为再怎么强调都不为过。 然而,很多人...
据IDC评述网(idcps.com)报道,ntldstats.com最新数据显示,截止至2016年3月31...
国内领先电商服务商——班牛通过阿里云数据库RDS从0到1搭建电商服务平台,目前已...
如何买 域名 和空间?网站是由网站程序,域名及 网站空间 组成的,无论是企业还...
本文转载自公众号读芯术(ID:AI_Discovery) 随着最新趋势被引入IT领域,QA测试有...