forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswap-adjacent-in-lr-string.cpp
43 lines (42 loc) · 1.32 KB
/
swap-adjacent-in-lr-string.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Time: O(n)
// Space: O(1)
// the followings are invariant if the number of 'X' in both strings are the same
// 1. the ordering of 'L', 'R' in both strings are the same
// 2. for each position (i, j) of paired 'L' character in both strings, i >= j
// 3. for each position (i, j) of paired 'R' character in both strings, i <= j
class Solution {
public:
bool canTransform(string start, string end) {
int count = 0;
for (int i = 0; i < size(start); ++i) {
if (start[i] == 'X') {
++count;
}
if (end[i] == 'X') {
--count;
}
}
if (count) {
return false;
}
for (int i = 0, j = 0; i < size(start) && j < size(end); ++i, ++j) {
while (i < size(start) && start[i] == 'X') {
++i;
}
while (j < size(end) && end[j] == 'X') {
++j;
}
if ((i < size(start)) != (j < size(end))) {
return false;
}
if (i < size(start) && j < size(end)) {
if (start[i] != end[j] ||
(start[i] == 'L' && i < j) ||
(start[i] == 'R' && i > j)) {
return false;
}
}
}
return true;
}
};