1790. Check if One String Swap Can Make Strings Equal #1273
-
Topics: You are given two strings Return Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine if we can make two given strings equal by performing at most one string swap on exactly one of the strings. Approach
Let's implement this solution in PHP: 1790. Check if One String Swap Can Make Strings Equal <?php
/**
* @param String $s1
* @param String $s2
* @return Boolean
*/
function areAlmostEqual($s1, $s2) {
if ($s1 === $s2) {
return true;
}
$diff = [];
for ($i = 0; $i < strlen($s1); $i++) {
if ($s1[$i] != $s2[$i]) {
array_push($diff, $i);
}
if (count($diff) > 2) {
return false;
}
}
if (count($diff) != 2) {
return false;
}
$i = $diff[0];
$j = $diff[1];
return ($s1[$i] == $s2[$j] && $s1[$j] == $s2[$i]);
}
// Example usage
$s1 = "bank";
$s2 = "kanb";
var_dump(canSwapToMakeEqual($s1, $s2)); // Output: true
$s1 = "attack";
$s2 = "defend";
var_dump(canSwapToMakeEqual($s1, $s2)); // Output: false
$s1 = "kelb";
$s2 = "kelb";
var_dump(canSwapToMakeEqual($s1, $s2)); // Output: true
?> Explanation:
Complexity:
This approach efficiently checks the necessary conditions with a time complexity of O(n), where n is the length of the strings, ensuring optimal performance. |
Beta Was this translation helpful? Give feedback.
We need to determine if we can make two given strings equal by performing at most one string swap on exactly one of the strings.
Approach
true
immediately as no swap is needed.false
because a single swap can only correct two differing positions.