码迷,mamicode.com
首页 > 其他好文 > 详细

longest-repeating-character-replacement(难)

时间:2016-10-16 23:43:46      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

用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;
    }
}

 

longest-repeating-character-replacement(难)

标签:

原文地址:http://www.cnblogs.com/charlesblc/p/5967989.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!