博客
关于我
【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/

你可能感兴趣的文章
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
查看>>
org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
查看>>
org.apache.poi.hssf.util.Region
查看>>
org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
查看>>
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
查看>>
org.hibernate.HibernateException: Unable to get the default Bean Validation factory
查看>>
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
查看>>
org.tinygroup.serviceprocessor-服务处理器
查看>>
org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
查看>>
org/hibernate/validator/internal/engine
查看>>
SQL-36 创建一个actor_name表,将actor表中的所有first_name以及last_name导入改表。
查看>>
ORM sqlachemy学习
查看>>
Ormlite数据库
查看>>
orm总结
查看>>
os.environ 没有设置环境变量
查看>>
os.path.join、dirname、splitext、split、makedirs、getcwd、listdir、sep等的用法
查看>>
os.system 在 Python 中不起作用
查看>>