博客
关于我
【Lintcode】1246. Longest Repeating Character Replacement
阅读量:195 次
发布时间:2019-02-28

本文共 1014 字,大约阅读时间需要 3 分钟。

双指针法是解决这个问题的高效方法。通过维护一个区间[j, i],并用count数组记录区间内每个字母的出现次数。当区间内的字符总数减去出现次数最多的字母的出现次数大于k时,右移左指针j,直到满足条件。每次满足条件时,更新最长子串的长度。

思路解析

  • 双指针维护区间:使用左右两个指针j和i来确定当前的区间[j, i]。j从左向右移动,i从左向右扩展。
  • 记录字母出现次数:使用count数组记录区间内每个字母的出现次数。
  • 检查条件:当区间内的总字符数减去出现次数最多的字母的次数大于k时,右移j,直到满足条件。
  • 更新最长子串长度:每次满足条件时,计算区间长度并更新最大值。

代码解析

public class Solution {    public int characterReplacement(String s, int k) {        int[] count = new int[26];        int res = 0;        for (int i = 0, j = 0; i < s.length(); i++) {            count[s.charAt(i) - 'A']++;            while (!check(count, k)) {                count[s.charAt(j) - 'A']--;                j++;            }            res = Math.max(res, i - j + 1);        }        return res;    }    private boolean check(int[] count, int k) {        int sum = 0, max = 0;        for (int i : count) {            sum += i;            max = Math.max(max, i);        }        return sum - max <= k;    }}

时间复杂度

  • O(n):每个字符只被处理一次,时间复杂度为O(n)。
  • 空间复杂度:使用了一个固定大小的数组count,空间复杂度为O(1)。

这个方法高效且简洁,能够在O(n)的时间内解决问题,适用于长字符串。

转载地址:http://xkjs.baihongyu.com/

你可能感兴趣的文章
NIO Selector实现原理
查看>>
NISP一级,NISP二级报考说明,零基础入门到精通,收藏这篇就够了
查看>>
NI笔试——大数加法
查看>>
NLP 基于kashgari和BERT实现中文命名实体识别(NER)
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
Node JS: < 一> 初识Node JS
查看>>
Node-RED中实现HTML表单提交和获取提交的内容
查看>>
node.js 怎么新建一个站点端口
查看>>
Node.js 文件系统的各种用法和常见场景
查看>>
node.js 配置首页打开页面
查看>>
node.js+react写的一个登录注册 demo测试
查看>>