作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/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. 1 <= len(start) = len(end) <= 10000.
  2. Both start and end will only consist of characters in {‘L’, ‘R’, ‘X’}.

题目大意

给出了一个初始的字符串,可以把初始字符串中的XL换成LX,可以把初始字符串中的RX换成XR,求问能不能通过一定的次数之后,把初始字符串变成结束字符串。

解题方法

智商题

本来以为是类似于迷宫的搜索问题,看到数据规模这么大,感觉不像,一看tag果然是智商题,那我就放弃了,智商不够用啊。

题目说了可以把初始字符串中的XL换成LX,可以把初始字符串中的RX换成XR,那么也就是说初始字符串中的L只能向左移动,初始字符串中R只能向右移动。并且L和R是不可能交换顺序的,两个字符串的L和R对应次数应该相等。知道这个规律之后,就使用双指针去解决就好了。

用i,j分别指向start和end的起始位置,如果他们指向的是X,那么都向右移动到不是X的位置,那么他们指向的字符应该相等,否则返回False。如果指向的是L,那么,start中的L的索引一定只能比end中L的索引小;如果指向的是R,那么,end中的R的索引一定只能比end中R的索引大。在while的结束之前需要把i和j同时向后移动。

全部判断完成之后返回True.

时间复杂度是O(N),空间复杂度是O(1).

class Solution(object):
def canTransform(self, start, end):
"""
:type start: str
:type end: str
:rtype: bool
"""
i, j = 0, 0
N = len(start)
while i < N and j < N:
while i < N - 1 and start[i] == 'X':
i += 1
while j < N - 1 and end[j] == 'X':
j += 1
if start[i] != end[j]:
return False
if start[i] == 'L' and i < j:
return False
if start[i] == 'R' and i > j:
return False
i += 1
j += 1
return True

相似题目

参考资料

http://www.cnblogs.com/grandyang/p/9001474.html

日期

2018 年 10 月 30 日 —— 啊,十月过完了

最新文章

  1. HashMap与TreeMap源码分析
  2. 在linux下Ant的环境配置
  3. Meet Sccot Guthrie in Shanghai
  4. 创建控制器的方法、控制器加载view过程、控制器view的生命周期、多控制器组合
  5. UITableViewCell 自定义绘制 性能高
  6. 分享使用method swizzling的经历
  7. sqlite3 C接口
  8. SDUTOJ 1489 求二叉树的先序遍历
  9. Redis参数配置和运维说明
  10. eclipse查看类源码出现failed to create the part&#39;s controls的解决方法
  11. Why Are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated ?
  12. Android简易实战教程--第三十二话《使用Lrucache和NetworkImageView加载图片》
  13. codeforces 982B Bus of Characters
  14. 安全运维之:Linux后门入侵检测工具的使用
  15. 12,EasyNetQ-自动订阅
  16. 常见sql注入的防范总结
  17. 【Alpha阶段】M1事后报告
  18. 【codevs1065】01字符串
  19. java反射bean to bean
  20. springmvc+jquery实现省市区地址下拉框联动

热门文章

  1. android 点击图片从Fragment跳转到activity
  2. mysql 不等于 符号写法
  3. 省时省心DTM,广告转化无难题
  4. addict, address, adequate.四级
  5. 基于MQTT协议实现远程控制的&quot;智能&quot;车
  6. Shell脚本的条件控制和循环语句
  7. Mysql的索引调优详解:如何去创建索引以及避免索引失效
  8. spring boot集成mybatis框架
  9. Java资源下载
  10. Spring Boot Actuator:健康检查、审计、统计和监控