publicintequalSubstring(String s, String t, int maxCost){ int res = 0; int[] dis = newint[s.length()]; char[] sArr = s.toCharArray(); char[] tArr = t.toCharArray();
//统计s[i]和t[i]的差距 for (int i = 0; i < s.length(); i++) { dis[i] = Math.abs(sArr[i] - tArr[i]); }
//因为子字符串要求连续,所以滑动窗口 int l = 0, r = 0, len = 0; while (r < s.length()){ if ((len + dis[r]) <= maxCost){ len += dis[r]; r++; }else { len -= dis[l]; l++; } res = Math.max(res, r - l); }
return res; }
python实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
defequalSubstring(self, s: str, t: str, maxCost: int) -> int: # 统计s[i]和t[i]的差距 dis = [abs(ord(s[i]) - ord(t[i])) for i in range(len(s))]
# 因为子字符串要求连续,所以滑动窗口 l, r, max_len, res = 0, 0, 0, 0 while r < len(s): if max_len + dis[r] <= maxCost: max_len += dis[r] r += 1 else: max_len -= dis[l] l += 1 res = max(res, r - l)