zoukankan      html  css  js  c++  java
  • [Swift]LeetCode293. 翻转游戏 $ Flip Game

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
    ➤微信公众号:山青咏芝(shanqingyongzhi)
    ➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
    ➤GitHub地址:https://github.com/strengthen/LeetCode
    ➤原文地址:https://www.cnblogs.com/strengthen/p/10692426.html 
    ➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
    ➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

    You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + and -, you and your friend take turns to flip twoconsecutive "++" into "--". The game ends when a person can no longer make a move and therefore the other person will be the winner.

    Write a function to compute all possible states of the string after one valid move.

    For example, given s = "++++", after one move, it may become one of the following states:

    [ "--++",  "+--+",  "++--"] 

    If there is no valid move, return an empty list [].


    您正在和您的朋友玩以下翻转游戏:给定一个仅包含这两个字符的字符串:+和-,您和您的朋友轮流将两个插入“++”翻转为“--”。游戏结束时,一个人不能再做一个动作,因此另一个人将是赢家。

    写一个函数来计算一次有效移动后字符串的所有可能状态。

    例如,给定s=“+++++”,移动一次后,它可能成为以下状态之一:

    [ "--++",  "+--+",  "++--"] 

    如果没有有效的移动,请返回空列表[]。


    Solution:

     1 class Solution {
     2     func generatePossibleNextMoves(_ s:String) ->[String] {
     3         var res:[String] = [String]()
     4         var arrS:[Character] = Array(s)
     5         for i in 1..<s.count
     6         {
     7             if arrS[i] == "+" && arrS[i - 1] == "+"
     8             {
     9                 res.append(s.subString(0, i - 1) + "--" + s.subString(i + 1))
    10             }
    11         }
    12         return res          
    13     }
    14 }
    15 
    16 extension String {
    17     // 截取字符串:从index到结束处
    18     // - Parameter index: 开始索引
    19     // - Returns: 子字符串
    20     func subString(_ index: Int) -> String {
    21         let theIndex = self.index(self.endIndex, offsetBy: index - self.count)
    22         return String(self[theIndex..<endIndex])
    23     }
    24     
    25     // 截取字符串:指定索引和字符数
    26     // - begin: 开始截取处索引
    27     // - count: 截取的字符数量
    28     func subString(_ begin:Int,_ count:Int) -> String {
    29         let start = self.index(self.startIndex, offsetBy: max(0, begin))
    30         let end = self.index(self.startIndex, offsetBy:  min(self.count, begin + count))
    31         return String(self[start..<end]) 
    32     }
    33 }
  • 相关阅读:
    BZOJ2199[Usaco2011 Jan]奶牛议会——2-SAT+tarjan缩点
    BZOJ3862Little Devil I——树链剖分+线段树
    BZOJ2325[ZJOI2011]道馆之战——树链剖分+线段树
    BZOJ1018[SHOI2008]堵塞的交通——线段树
    BZOJ2733[HNOI2012]永无乡——线段树合并+并查集+启发式合并
    BZOJ4127Abs——树链剖分+线段树
    bzoj 4753 最佳团体
    bzoj 4472 salesman
    bzoj 5369 最大前缀和
    bzoj 1226 学校食堂Dining
  • 原文地址:https://www.cnblogs.com/strengthen/p/10692426.html
Copyright © 2011-2022 走看看