• longest-repeating-character-replacement(难)


    用sliding window的方法,之前还有个k不同元素好像也是类似的思路。有时间可以去复习下。

    https://leetcode.com/problems/longest-repeating-character-replacement/
    
    // sliding window
    
    public class Solution {
        public int characterReplacement(String s, int k) {
    
            int[] count = new int[26];
            
            int maxch = -1; // the char with max count in current substr
            int max = 0; // the max count for single char in current substr
            int len = 0; // current substr length
            int ret = 0; // final result
    
            for (int i=0; i<s.length(); i++) {
                int tmp = s.charAt(i) - 'A';
                count[tmp]++;
                len++;
    
                if (maxch == tmp) {
                    max++;
                }
                else {
                    if (count[tmp] > max) {
                        max = count[tmp];
                        maxch = tmp;
                    }
                }
    
                if (len - max <= k) {
                    if (len > ret) {
                        ret = len;
                    }
                }
    
                while (len - max > k) {
                    int newTmp = s.charAt(i-len+1) - 'A';
                    count[newTmp]--;
                    len--;
                    if (maxch == newTmp) {
                        max--;
                        for (int j=0; j<26; j++) {
                            if (count[j] > max) {
                                max = count[j];
                                maxch = j;
                            }
                        }
                    }
                }
            }
            return ret;
        }
    }
  • 相关阅读:
    读入输出优化
    【JSOI2008】星球大战 并查集
    堆STL和重载运算符
    树的直径
    H3C三层交换机(S5500)清除配置信息并进行简单配置
    简单的逻辑学
    Java基础--第十八天
    Java基础--第十七天
    Java基础--第十六天
    Java基础--第十五天
  • 原文地址:https://www.cnblogs.com/charlesblc/p/5967989.html
Copyright © 2020-2023  润新知