Skip to content

Commit 7fab3bd

Browse files
authored
Create minimum-swaps-to-make-strings-equal.cpp
1 parent 9f497ce commit 7fab3bd

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int minimumSwap(string s1, string s2) {
7+
int x1 = 0, y1 = 0;
8+
for (int i = 0; i < s1.length(); ++i) {
9+
if (s1[i] == s2[i]) {
10+
continue;
11+
}
12+
x1 += int(s1[i] == 'x');
13+
y1 += int(s1[i] == 'y');
14+
}
15+
if (x1 % 2 != y1 % 2) { // impossible
16+
return -1;
17+
}
18+
// case1: per xx or yy needs one swap, (x1 / 2 + y1 / 2)
19+
// case2: per xy or yx needs two swaps, (x1 % 2 + y1 % 2)
20+
return x1 / 2 + y1 / 2 + x1 % 2 + y1 % 2;
21+
}
22+
};

0 commit comments

Comments
 (0)