Skip to content

Commit ea2ff4e

Browse files
committed
Add solution #777
1 parent cb92bea commit ea2ff4e

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -587,6 +587,7 @@
587587
770|[Basic Calculator IV](./0770-basic-calculator-iv.js)|Hard|
588588
773|[Sliding Puzzle](./0773-sliding-puzzle.js)|Hard|
589589
775|[Global and Local Inversions](./0775-global-and-local-inversions.js)|Medium|
590+
777|[Swap Adjacent in LR String](./0777-swap-adjacent-in-lr-string.js)|Medium|
590591
783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy|
591592
784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium|
592593
790|[Domino and Tromino Tiling](./0790-domino-and-tromino-tiling.js)|Medium|
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* 777. Swap Adjacent in LR String
3+
* https://leetcode.com/problems/swap-adjacent-in-lr-string/
4+
* Difficulty: Medium
5+
*
6+
* In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either
7+
* replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given
8+
* the starting string start and the ending string result, return True if and only if there exists
9+
* a sequence of moves to transform start to result.
10+
*/
11+
12+
/**
13+
* @param {string} start
14+
* @param {string} result
15+
* @return {boolean}
16+
*/
17+
var canTransform = function(start, result) {
18+
if (start.replace(/X/g, '') !== result.replace(/X/g, '')) {
19+
return false;
20+
}
21+
22+
let i = 0;
23+
let j = 0;
24+
const n = start.length;
25+
26+
while (i < n && j < n) {
27+
while (i < n && start[i] === 'X') i++;
28+
while (j < n && result[j] === 'X') j++;
29+
30+
if (i === n && j === n) return true;
31+
if (i === n || j === n) return false;
32+
33+
if (start[i] !== result[j]) return false;
34+
35+
if (start[i] === 'L' && i < j) return false;
36+
if (start[i] === 'R' && i > j) return false;
37+
38+
i++;
39+
j++;
40+
}
41+
42+
return true;
43+
};

0 commit comments

Comments
 (0)