intbinarySearch(int* accDiff, int endIndex, int target) { int low = 0, high = endIndex; while (low < high) { int mid = (high - low) / 2 + low; if (accDiff[mid] < target) { low = mid + 1; } else { high = mid; } } return low; }
intequalSubstring(char* s, char* t, int maxCost) { int n = strlen(s); int accDiff[n + 1]; memset(accDiff, 0, sizeof(accDiff)); for (int i = 0; i < n; i++) { accDiff[i + 1] = accDiff[i] + fabs(s[i] - t[i]); } int maxLength = 0; for (int i = 1; i <= n; i++) { int start = binarySearch(accDiff, i, accDiff[i] - maxCost); maxLength = fmax(maxLength, i - start); } return maxLength; }
classSolution { public: intequalSubstring(string s, string t, int maxCost){ int n = s.length(); vector<int> diff(n, 0); for (int i = 0; i < n; i++) { diff[i] = abs(s[i] - t[i]); } int maxLength = 0; int start = 0, end = 0; int sum = 0; while (end < n) { sum += diff[end]; while (sum > maxCost) { sum -= diff[start]; start++; } maxLength = max(maxLength, end - start + 1); end++; } return maxLength; } };
funcequalSubstring(s string, t string, maxCost int) (maxLen int) { n := len(s) diff := make([]int, n) for i, ch := range s { diff[i] = abs(int(ch) - int(t[i])) } sum, start := 0, 0 for end, d := range diff { sum += d for sum > maxCost { sum -= diff[start] start++ } maxLen = max(maxLen, end-start+1) } return }
funcabs(x int)int { if x < 0 { return -x } return x }
funcmax(a, b int)int { if a > b { return a } return b }
[sol2-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: defequalSubstring(self, s: str, t: str, maxCost: int) -> int: n = len(s) diff = [abs(ord(sc) - ord(tc)) for sc, tc inzip(s, t)] maxLength = start = end = 0 total = 0
while end < n: total += diff[end] while total > maxCost: total -= diff[start] start += 1 maxLength = max(maxLength, end - start + 1) end += 1 return maxLength
intequalSubstring(char* s, char* t, int maxCost) { int n = strlen(s); int diff[n]; memset(diff, 0, sizeof(diff)); for (int i = 0; i < n; i++) { diff[i] = fabs(s[i] - t[i]); } int maxLength = 0; int start = 0, end = 0; int sum = 0; while (end < n) { sum += diff[end]; while (sum > maxCost) { sum -= diff[start]; start++; } maxLength = fmax(maxLength, end - start + 1); end++; } return maxLength; }
复杂度分析
时间复杂度:O(n),其中 n 是字符串的长度。 计算数组 diff 的时间复杂度是 O(n)。 遍历数组的过程中,两个指针的移动次数都不会超过 n 次。 因此总时间复杂度是 O(n)。