Swap Adjacent in LR String

In a string composed of de >'L'de>, de >'R'de>, and de >'X'de> characters, like de >"RXXLRXRXL"de>, a move consists of either replacing one occurrence of de >"XL"de> with de >"LX"de>, or replacing one occurrence of de >"RX"de> with de >"XR"de>. Given the starting string de >startde> and the ending string de >endde>, return de >Truede> if and only if there exists a sequence of moves to transform one string to the other.

Example:

Input: start = "RXXLRXRXL", end = "XRLXXRRLX"
Output: True
Explanation:
We can transform start to end following these steps:
RXXLRXRXL ->
XRXLRXRXL ->
XRLXRXRXL ->
XRLXXRRXL ->
XRLXXRRLX

Note:

  1. de >1 <= len(start) = len(end) <= 10000de>.
  2. Both start and end will only consist of characters in de >{'L', 'R', 'X'}de>.

根据题目的描述,L和R可以移动,因此只需要start和end这两个字符串里L和R的相对位置相同就可以。又考虑到,L只能向左移动,R只能向右移动,因此对应位置的L,start中的L只能在end中L的右边(或者同一位置),对应位置的R,start中的R只能在end中的R的左边(或者同一位置),代码如下:

class Solution {
    public boolean canTransform(String start, String end) {
        char[] chs = start.toCharArray(), che = end.toCharArray();
        if(chs.length != end.length())
        	return false;
        int i = 0, j = 0, len = chs.length;
        while(true){
        	while(i < chs.length && chs[i] == 'X')
        		i++;
        	while(j < che.length && che[j] == 'X')
        		j++;
        	//System.out.println(i + " " + j);
        	if(i == len && j == len)
        		return true;
        	if(i == len || j == len)
        		return false;
        	if(chs[i] != che[j])
        		return false;
            if(chs[i] == 'R' && i > j || chs[i] == 'L' && i < j)
        		return false;
        	i++;j++;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值