1208. Get Equal Substrings Within Budget #255
-
Topics: You are given two strings You want to change Return the maximum length of a substring of Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The problem asks us to find the maximum length of a substring in string Key Points:
Approach:
Plan:
Let's implement this solution in PHP: 1208. Get Equal Substrings Within Budget <?php
/**
* @param String $s
* @param String $t
* @param Integer $maxCost
* @return Integer
*/
function equalSubstring($s, $t, $maxCost) {
$j = 0;
for ($i = 0; $i < strlen($s); ++$i) {
$maxCost -= abs(ord($s[$i]) - ord($t[$i]));
if ($maxCost < 0)
$maxCost += abs(ord($s[$j]) - ord($t[$j++]));
}
return strlen($s) - $j;
}
// Example usage:
$s = "abcd";
$t = "bcdf";
$maxCost = 3;
echo equalSubstring($s, $t, $maxCost) . "\n"; // Output: 3
$s = "abcd";
$t = "cdef";
$maxCost = 3;
echo equalSubstring($s, $t, $maxCost) . "\n"; // Output: 1
$s = "abcd";
$t = "acde";
$maxCost = 0;
echo equalSubstring($s, $t, $maxCost) . "\n"; // Output: 1
?> Explanation:
Example Walkthrough:Example 1: $s = "abcd";
$t = "bcdf";
$maxCost = 3;
Example 2: $s = "abcd";
$t = "cdef";
$maxCost = 3;
Time Complexity:
Output for Example:Example 1: $s = "abcd";
$t = "bcdf";
$maxCost = 3;
Example 2: $s = "abcd";
$t = "cdef";
$maxCost = 3;
The sliding window approach efficiently solves the problem by maintaining a valid substring whose transformation cost does not exceed |
Beta Was this translation helpful? Give feedback.
The problem asks us to find the maximum length of a substring in string
s
that can be transformed into a substring in stringt
with a cost not exceedingmaxCost
. The cost of changing a character is the absolute difference between the ASCII values of corresponding characters ins
andt
. We need to determine the longest substring that can be changed without exceeding the givenmaxCost
.Key Points:
maxCost
.