LeetCode 395. Longest Substring with At Least K Repeating Characters C#
2024-08-30 09:01:36
Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times.
Example 1:
Input:
s = "aaabb", k = 3 Output:
3 The longest substring is "aaa", as 'a' is repeated 3 times.
Example 2:
Input:
s = "ababbc", k = 2 Output:
5 The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.
Solution:
Map all characters in string s to a Hash map and store the count of characters as values.
if all characters occur more than k times, then return the whole string length as result;
if not, find the least occured character and split the string by this char, then call this function recursively
to get the max length out of all substrings.
return the max.
public class Solution {
public int LongestSubstring(string s, int k) {
Dictionary<char,int> map = new Dictionary<char, int>();
if(string.IsNullOrEmpty(s))
{
return ;
}
int l = s.Length;
for(int i=; i<l; i++)
{
if(map.ContainsKey(s[i]))
{
map[s[i]]++;
}
else
{
map.Add(s[i],);
}
}
char minKey=map.Aggregate((p, r) => p.Value < r.Value ? p : r).Key;
if(map[minKey]>=k)
{
return l;
}
string[] splitted = s.Split(minKey);
int max = ;
foreach(string n in splitted)
{
int m = LongestSubstring(n,k);
if(m>max)
{
max = m;
}
}
return max; }
}
最新文章
- 简单讲解MVC(视图/模型/控制器)
- 用POI读取具有任意合并单元的excel数据
- HD 1003 Max Sum 的递归解法
- 【Scala学习笔记】第01弹——Scala安装与配置
- jsp无法支持el标签及jstl标签
- poj2586
- Scala学习笔记--xml
- 关于hibernate非主键多对一关联
- 给FPGA初学者的建议——不要浮躁(转)
- WindowsService服务的C#实现
- Java中常见数据结构List之ArrayList
- Node.js初探之实现能向前台返回东西的简单服务器
- 进程与线程的通信机制----Queue
- python MySQLdb 字段与关键字重名
- Android——listview android:cacheColorHint,android:listSelector属性作用
- 8-13 Just Finish it up uva11093
- .net垃圾回收
- 15.Git面试题
- let 和 var 区别
- No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer解决方法
热门文章
- reading words in your computer and changing to female voice, linux festival text2wave saving wav files
- PPT资料下载 - 问题驱动的软件测试设计:强化测试用例设计
- SQL 两表关联查询 where 条件中等号两端字段顺序对效率的影响
- php学习笔记——语言切换
- Ubuntu16.04删除客人会话
- express 4.x 文件上传
- [转]Numpy使用MKL库提升计算性能
- sort vector - leetcode 新用法
- ngDialog 设置其宽度大小
- VS生成桌面应用程序