Skip to content

Commit 447a02d

Browse files
committed
1790
1 parent c5d1cfd commit 447a02d

File tree

1 file changed

+31
-5
lines changed
  • Easy/1790. Check if One String Swap Can Make Strings Equal

1 file changed

+31
-5
lines changed
Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,39 @@
11
<?php
2+
class Solution
3+
{
4+
/**
5+
* @param String $s1
6+
* @param String $s2
7+
* @return Boolean
8+
*/
9+
public function areAlmostEqual($s1, $s2)
10+
{
11+
if ($s1 === $s2) {
12+
return true;
13+
}
214

3-
class Solution {
15+
$diff = [];
416

5-
6-
function areAlmostEqual($s1, $s2) {
7-
17+
// Find positions where characters differ
18+
for ($i = 0; $i < strlen($s1); $i++) {
19+
if ($s1[$i] !== $s2[$i]) {
20+
$diff[] = $i;
21+
}
22+
}
23+
24+
// If there are exactly two differences, check if swapping them fixes the strings
25+
return count($diff) === 2 &&
26+
$s1[$diff[0]] === $s2[$diff[1]] &&
27+
$s1[$diff[1]] === $s2[$diff[0]];
828
}
929
}
1030

31+
$solution = new Solution();
32+
33+
$s1 = "abcd";
34+
35+
$s2 = "dcba";
1136

37+
$result = $solution->areAlmostEqual($s1, $s2); // Output: true
1238

13-
?>
39+
print_r($result);

0 commit comments

Comments
 (0)