首页 > 代码库 > longest-substring-with-at-least-k-repeating-characters
longest-substring-with-at-least-k-repeating-characters
https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/public class Solution { public int longestSubstring(String s, int k) { // Find count of each char HashMap mp = new HashMap(); Object intObj; for (int i=0; i<s.length(); i++) { char ch = s.charAt(i); intObj = mp.remove(ch); int st = 0; if (intObj != null) { st = (int) intObj; } st++; mp.put(ch, st); } // prepre iterate secondly int ret = 0; int last = -1; HashMap newMp = new HashMap(); // iterate secondly for (int i=0; i<s.length(); i++) { char ch = s.charAt(i); int num = (int)mp.get(ch); // pass if num fits if (num >= k) { intObj = newMp.get(ch); int newNum = 0; if (intObj != null) { newNum = (int) intObj; } newNum++; newMp.put(ch, newNum); continue; } // handle if meets nofit char Set filter = new HashSet(); Iterator iter = newMp.entrySet().iterator(); Map.Entry entry; // check newMp and prepare filter while (iter.hasNext()) { entry = (Map.Entry) iter.next(); char cch = (char)entry.getKey(); int cnt = (int)entry.getValue(); if (cnt < k) { filter.add(cch); } int allCnt = (int)mp.remove(cch); allCnt -= cnt; mp.put(cch, allCnt); } // Prune if (filter.size() == newMp.size()) { last = i; newMp.clear(); continue; } // use filter to check each segment HashMap fMp = new HashMap(); int newLast = last; for (int j=last+1; j<=i; j++) { char fch = ‘ ‘; if (j < i) { fch = s.charAt(j); } // need to check segment if (j == i || filter.contains(fch)) { iter = fMp.entrySet().iterator(); boolean fits = true; // check map of each segment while (iter.hasNext()) { entry = (Map.Entry) iter.next(); char ffch = (char)entry.getKey(); int fcnt = (int)entry.getValue(); if (fcnt < k) { fits = false; } // Prepare Prune by update newMp int newCnt = (int)newMp.remove(ffch); newCnt -= fcnt; newMp.put(ffch, newCnt); if (newCnt < k) { filter.add(ffch); } } // update final ret if (fits) { if (j-newLast-1 > ret) { ret = j-newLast-1; } } newLast = j; fMp.clear(); // Check Prune if (filter.size() == newMp.size()) { break; } } // no need to check segment, pass else { intObj = fMp.get(fch); int fNum = 0; if (intObj != null) { fNum = (int) intObj; } fNum++; fMp.put(fch, fNum); } } newMp.clear(); last = i; } if (s.length()-last-1 > ret) { ret = s.length()-last-1; } return ret; }}test case:"zzzzzzzzzzaaaaaaaaabbbbbbbbhbhbhbhbhbhbhicbcbcibcbccccccccccbbbbbbbbaaaaaaaaafffaahhhhhiaahiiiiiiiiifeeeeeeeeee"10expected return: 21
longest-substring-with-at-least-k-repeating-characters
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。