• 【LeetCode】智商题 brainteaser(共3题)


    【292】Nim Game 

    【319】Bulb Switcher 

    【777】Swap Adjacent in LR String (2019年2月13日,谷歌tag)

    给了两个字符串start 和end,问通过如下两个规则能不能经过一定的变换,把start变成end。

    规则1: "XL" -> "LX" 

    规则2:"RX"->"XR"

    题解:我一开始还以为贪心能解。结果==,举个例子 start = "XXXXXLXXXX" end = "LXXXXXXXXX",这样是能够变换过去的。

    通过观察我们可以得到如下的结论:L只能往左移动,R只能往右移动,而且两个都是只能和X交换。所以。我们可以检查整个字符串除了X之外的所有字符LR,看start和end除了X之外的字符是不是相等。如果不是,那么肯定不能变换出来。

    还有,因为L只能往左边移动,而且只能和X交换。那么我们start中的L如果它的下标位置比end中的L的下标位置小的话,这样肯定是不行的。同理R。

    时间复杂度是O(N)

     1 class Solution {
     2 public:
     3     bool canTransform(string start, string end) {
     4         const int n = start.size();
     5         int p1 = 0, p2 = 0;
     6         while (p1 < n && p2 < n) {
     7             while (p1 < n && start[p1] == 'X') {++p1;}
     8             while (p2 < n && end[p2] == 'X') {++p2;}
     9             if (p1 == n && p2 == n) {break;}
    10             if (p1 < n && p2 == n || p1 == n && p2 < n || start[p1] != end[p2]) {return false;}
    11             if (start[p1] == 'L' && p1 < p2) {return false;}
    12             if (start[p1] == 'R' && p1 > p2) {return false;}
    13             ++p1, ++p2;
    14         }
    15         return true;
    16     }
    17 };
    View Code
  • 相关阅读:
    分页精度
    abp zero core 启动vue项目
    swagger 配置错误
    .net core 3.0配置跨域
    .net core 3.0 swagger
    .net core 3.0一个记录request和respose的中间件
    .net Core3.0 +Nlog+Sqlserver
    .net core 3.0+unit of work (一)
    .NetCore 3.0迁移遇到的各种问题
    open xml 导出excel遇到的问题
  • 原文地址:https://www.cnblogs.com/zhangwanying/p/9964669.html
Copyright © 2020-2023  润新知