File tree Expand file tree Collapse file tree 1 file changed +31
-5
lines changed
Easy/1790. Check if One String Swap Can Make Strings Equal Expand file tree Collapse file tree 1 file changed +31
-5
lines changed Original file line number Diff line number Diff line change 1
1
<?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
+ }
2
14
3
- class Solution {
15
+ $ diff = [];
4
16
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 ]];
8
28
}
9
29
}
10
30
31
+ $ solution = new Solution ();
32
+
33
+ $ s1 = "abcd " ;
34
+
35
+ $ s2 = "dcba " ;
11
36
37
+ $ result = $ solution ->areAlmostEqual ($ s1 , $ s2 ); // Output: true
12
38
13
- ?>
39
+ print_r ( $ result );
You can’t perform that action at this time.
0 commit comments