当前位置:网站首页>Xiaohei's leetcode journey: 95. Longest substring with at least K repeating characters
Xiaohei's leetcode journey: 95. Longest substring with at least K repeating characters
2022-08-04 23:20:00 【little black invincible】
小黑java解法1:分治法
class Solution {
public int longestSubstring(String s, int k) {
return dfs(s, 0, s.length() - 1, k);
}
public int dfs(String s, int left, int right, int k) {
if (left > right) {
return 0;
}
int[] cnt = new int[26];
for (int i = left; i <= right; i++) {
cnt[s.charAt(i) - 'a']++;
}
int res = 0;
int start = left;
boolean flag = false;
System.out.println(left+"+"+right);
for(int i = left; i <= right; i++) {
if (cnt[s.charAt(i) - 'a'] < k) {
System.out.println(i);
int p = dfs(s, start, i-1, k);
if(p > res){
res = p;
}
flag = true;
start = i + 1;
}
}
if(flag){
int p = dfs(s, start, right, k);
if(p > res){
res = p;
}
return res;
}
return right - left + 1;
}
}

小黑python解法1:分治法
class Solution:
def longestSubstring(self, s: str, k: int) -> int:
l = len(s)
def substring(s,start,end):
counts = {
}
for c in s[start:end+1]:
counts[c] = counts.get(c,0) + 1
# 生成分割点
splits = []
for key in counts:
if counts[key] < k:
splits.append(key)
if not splits:
return end - start + 1
i = start
res = 0
while i <= end:
while i <= end and s[i] in splits:
i += 1
if i > end:
break
start = i
while i <= end and s[i] not in splits:
i += 1
length = substring(s,start,i-1)
res = max(length,res)
return res
return substring(s,0,l-1)

分治法
class Solution:
def longestSubstring(self, s: str, k: int) -> int:
l = len(s)
def subString(start,end):
counts = {
}
# Record the frequency of each character in the substring
for c in s[start:end+1]:
counts[c] = counts.get(c,0) + 1
# Filter out frequencies less thank的一个字符
split = None
for c in counts.keys():
if counts[c] < k:
split = c
break
# All characters meet the requirements,则return
if not split:
return end - start + 1
i = start
ans = 0
while start <= end:
while i <= end and s[i] == split:
i += 1
if i > end:
break
start = i
while i <= end and s[i] != split:
i += 1
ans = max(ans,subString(start,i-1))
return ans
return subString(0,l-1)

边栏推荐
猜你喜欢
随机推荐
MySQL增删改查基础
一点点读懂cpufreq(一)
Uniapp dynamic sliding navigation effect demo (finishing)
Go 语言快速入门指南:什么是 TSL 安全传输层
The Controller layer code is written like this, concise and elegant!
Since a new byte of 20K came out, I have seen what the ceiling is
Web安全开发 | 青训营笔记
Laravel 实现redis分布式锁
【3D建模制作技巧分享】ZBrush模型如何添加不同材质
Linear DP (bottom)
亿流量大考(3):不加机器,如何抗住每天百亿级高并发流量?
Service Mesh落地路径
被领导拒绝涨薪申请,跳槽后怒涨9.5K,这是我的心路历程
2022/8/4 树上差分+线段树
365天深度学习训练营-学习线路
功耗控制之DVFS介绍
Will we still need browsers in the future?(feat. Maple words Maple language)
NebulaGraph v3.2.0 Release Note, many optimizations such as the performance of querying the shortest path
社区分享|腾讯海外游戏基于JumpServer构建游戏安全运营能力
[Cultivation of internal skills of string functions] strcpy + strcat + strcmp (1)









