leetcode 777. Swap Adjacent in LR String | 777. 在LR字符串中交换相邻字符(双指针)

x33g5p2x  于2021-12-06 转载在 其他  
字(0.8k)|赞(0)|评价(0)|浏览(280)

题目

https://leetcode.com/problems/swap-adjacent-in-lr-string/

题解

本来以为是个带 visited 集合的 DFS,一看数据量,居然是 10^4。

然后看了下 hint,Think of the L and R's as people on a horizontal line, where X is a space. The people can't cross each other, and also you can't go from XRX to RXX.,一想,有点像状态机嘛。

详见草稿:

  1. class Solution {
  2. public boolean canTransform(String start, String end) {
  3. int i = 0;
  4. int j = 0;
  5. while (true) {
  6. while (i < start.length() && start.charAt(i) == 'X') i++;
  7. while (j < end.length() && end.charAt(j) == 'X') j++;
  8. if (i == start.length() && j == end.length()) return true;
  9. if (i == start.length() || j == end.length()) return false;
  10. if (i < start.length() && j < end.length() && start.charAt(i) == end.charAt(j)) { // 两字母相同
  11. if (start.charAt(i) == 'L') { // 均为L
  12. if (i < j) return false;
  13. } else { // 均为R
  14. if (j < i) return false;
  15. }
  16. i++;
  17. j++;
  18. } else { // 两字母不同
  19. return false;
  20. }
  21. }
  22. }
  23. }

相关文章