Give you the same string two lengths, s
and t
.
The s
the first i
character is changed to t
the first i
character requires |s[i] - t[i]|
overhead (cost may be 0), i.e. the absolute value of the difference between two values of the ASCII characters.
The maximum budget for the change of the string is maxCost
. When converting a string, the total cost should be less than or equal to the budget, it also means that transformed string may be incomplete.
If you can s
substring in converted to its t
corresponding sub-string, the return can be transformed into a maximum length.
If s
no substring can be converted to t
the corresponding sub-string is returned 0
.
Example 1:
Input: s = "abcd", t = "bcdf", cost = 3 Output: 3 explains: S of "abc" may become "bcd". The cost is 3, maximum length is 3.
Example 2:
Input: s = "abcd", t = "cdef", cost = 3
Output: 1
explains: a character S in any order into the corresponding t character, its overhead is 2. Therefore, the maximum length of 1。
Example 3:
Input: s = "abcd", t = "acde", cost = 0 Output: 1 Explanation: You can not make any changes, so the maximum length is 1.
prompt:
1 <= s.length, t.length <= 10^5
0 <= maxCost <= 10^6
s
And t
only contain lowercase letters.
First, write their own mistakes demonstration, overtime
1 int equalSubstring(string s, string t, int maxCost) { 2 int size = s.size(); 3 if (size == 0) 4 return 0; 5 vector<int> distance(size, 0); 6 for (int i = 0; i < size; i++) 7 { 8 distance[i] = abs(s[i] - t[i]); 9 } 10 for (auto e : distance) 11 cout << e << " "; 12 cout << endl; 13 int res = 0; 14 int tempres = 0; 15 int i = 0, j = 0; 16 int count = 0; 17 while (j < size) 18 { 19 count += distance[j]; 20 if (count <= maxCost) 21 { 22 j++; 23 tempres++; 24 res = max(res, tempres); 25 } 26 else 27 { 28 count = 0; 29 res = max(res, tempres); 30 tempres = 0; 31 i++; 32 j = i; 33 } 34 } 35 return res; 36 }