Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

777.在lr字符串中交换相邻字符 #7

Open
feikerwu opened this issue Mar 4, 2020 · 0 comments
Open

777.在lr字符串中交换相邻字符 #7

feikerwu opened this issue Mar 4, 2020 · 0 comments

Comments

@feikerwu
Copy link
Owner

feikerwu commented Mar 4, 2020

原题地址

在一个由 'L' , 'R' 和 'X' 三个字符组成的字符串(例如"RXXLRXRXL")中进行移动操作。一次移动操作指用一个"LX"替换 一个"XL",或者用一个"XR"替换一个"RX"。现给定起始字符串start和结束字符串end,请编写代码,当且仅当存在一系列移动 操作使得start可以转换成end时, 返回True。

题解

题目只需要求从start能否通过 'XL' => 'LX', 'RX' => 'XR' 操作到end, 观察到'XL'只能替换成'LX', 'RX'只能替换成'XR', 也就是'L'只能向左移动,'R'只能向右移动,且'L'和'R'不能交换。
所以要判断start 能否到达end,只需要满足以下两个条件即可

  1. start去掉'X'后的字符串 等于 end去掉'X'后的字符串
  2. 如果满足1,那么对每个满足start[p1] === end[p2] 的位置
    1. 如果start[p1] === 'L', 那么 p1 必须 >= p2, 因为 L 只能向左移动
    2. 同理,如果end[p1] === 'R', 那么 p1 必须 <= p2, 因为 R 只能向右移动

代码实现

/**
 * @param {string} start
 * @param {string} en
 * @return {boolean}
 */
var canTransform = function(start, end) {
  let startCopy = start
  let endCopy = end
  if (startCopy.replace(/X/g, '') !== endCopy.replace(/X/g, '')) {
    console.log('here')
    return false
  }
  let p1 = p2 = 0;
  while(p1 < start.length && p2 < end.length) {
    while(start[p1] === 'X') {
      p1++
    }
    while(end[p2] === 'X') {
      p2++
    }
    if (start[p1] !== end[p2]) {
      return false
    } else {
      if ((start[p1] === 'L' && p1 < p2) || (start[p1] === 'R' && p1 > p2)) {
        return false
      }
    }
    p1++;
    p2++;
  }
  return true
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant