LintCode:最多有k个不同字符的最长子字符串


给定一个字符串,找到最多有k个不同字符的最长子字符串。
您在真实的面试中是否遇到过这个题?  
Yes
样例

例如,给定 s = "eceba" , k = 3,

T 是 "eceb",长度为 4.

挑战

O(n), n 是所给字符串的长度

标签  Expand  

相关题目  Expand 
解题思路:
利用双指针,以及map实现。
用map记录每一个字符出现的次数,若该字符出现过,则将value加1,若是该字符没有出现过,增加该key,value=1。
在去判断map.size()是否大于k,大于减去slow指针的key所对应的map元素,否则直接计算该slow到fast指针的符合条件的数字。
public class Solution {
    /**
     * @param s : A string
     * @return : The length of the longest substring
     *           that contains at most k distinct characters.
     */
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        // write your code here
          if (s == null || s.length() == 0)
               return 0;
          int slow = 0;
          int res = 0;
          HashMap<Character, Integer> map = new HashMap<>();
          for (int fast = 0; fast < s.length(); fast++) {
               char c = s.charAt(fast);
               if (map.containsKey(c)) {
                    map.put(c, map.get(c) + 1);
               } else {
                    map.put(c, 1);
               }
               if(map.size()>k){
                    char tmp = s.charAt(slow++);
                    int count = map.get(tmp);
                    if(count-1>0){
                         map.put(tmp, count-1);
                    }else{
                         map.remove(tmp);
                    }
               }
               res = Math.max(res, fast-slow+1);
          }
          return res;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值