for (char c : targetArr) { targetCount[c]++; // 目标串中一个字符出现了几次 } intcount=0; // 需要满足多少个条件 for (int i : targetCount) { if (i > 0) { // 将一个字符看做一个条件,目标串中有多少种字符就有多少条件 count++; } }
intcounted=0;// 已经满足的条件 intleft=0; // 滑动窗口的起始位置 left Resultres=null; for (intright=0; right < sourceArr.length; right++) { // 滑动窗口的终止位置right charrightCh= sourceArr[right]; // 统计原始串 left~right 范围各种字符的个数 sourceCount[rightCh]++; // 如果原始串中字符出现的次数等于目标串中字符出现的次数 if (sourceCount[rightCh] == targetCount[rightCh]) { counted++; // 每满足一个条件,counted++ } while (left <= right && counted == count) { // 当前窗口满足所有条件后,尝试缩小窗口 // 找所有满足条件的解中,长度最小的 if (res == null) { res = newResult(left, right); } else { if ((right - left) < (res.right - res.left)) { res = newResult(left, right); } } // 开始移动left,找长度更小的解 charleftCh= sourceArr[left]; sourceCount[leftCh]--; // 如果原始串中字符出现的次数小于了目标串中字符出现的此时,将counted-- if (sourceCount[leftCh] < targetCount[leftCh]) { counted--; } left++; } } return res == null ? "" : newString(sourceArr, res.left, res.right - res.left + 1); } }