[leetcode] 777. Swap Adjacent in LR String

网友投稿 270 2022-08-26

[leetcode] 777. Swap Adjacent in LR String

Description

In a string composed of ‘L’, ‘R’, and ‘X’ characters, like “RXXLRXRXL”, a move consists of either replacing one occurrence of “XL” with “LX”, or replacing one occurrence of “RX” with “XR”. Given the starting string start and the ending string end, return True 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 <= len(start) = len(end) <= 10000.Both start and end will only consist of characters in {‘L’, ‘R’, ‘X’}.

分析

题目的意思是:给定start串和end串,L表示可以向左移,R可以向右移动,L和R只能根X交换位置,问start可不可以通过移动变成end串。

不论是L还是R,其只能跟X交换位置,L和R之间是不能改变相对顺序的,所以如果分别将start和end中所有的X去掉后的字符串不相等的话,那么就永远无法让start和end相等了。这个判断完之后,就来验证L只能前移,R只能后移这个限制条件吧,当i指向start中的L时,那么j指向end中的L必须要在前面,所以如果i小于j的话,就不对了,同理,当i指向start中的R,那么j指向end中的R必须在后面,所以i大于j就是错的,最后别忘了i和j同时要自增1,不然死循环了。

代码

class Solution {public: bool canTransform(string start, string end) { int i=0,j=0; int n=start.size(); while(ij&&start[i]=='R')){ return false; } i++; j++; } return true; }};

参考文献

​​[LeetCode] Swap Adjacent in LR String 交换LR字符串中的相邻项​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:[leetcode] 517. Super Washing Machines
下一篇:多平台整治旅游营销虚假宣传!(如何整治旅游乱象规范旅游市场)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~