敢教日月换新天。为有牺牲多壮志,

[Swift]LeetCode294. 翻转游戏之 II $ Flip Game II

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

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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 two consecutive "++" 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 determine if the starting player can guarantee a win.

Example:

s = "++++"
"++"
"+--+"

Follow up:
Derive your algorithm's runtime complexity.


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

写一个函数来确定首发球员是否能保证获胜。

例子:

输入:s = "++++"

输出:true

说明:先手玩家可以通过将中间“++”翻转成“+--+”来保证获胜。

跟进:

推导算法的运行时复杂性。


Solution:

复制代码
 1 class Solution {
 2     func canWin(_ s:String) -> Bool {
 3         var arrS:[Character] = Array(s)
 4         for i in 1..<s.count
 5         {
 6             if arrS[i] == "+" && arrS[i - 1] == "+" && !canWin(s.subString(0, i - 1) + "--" + s.subString(i + 1))
 7             {
 8                 return true
 9             }
10         }
11         return false          
12     }
13 }
14 
15 extension String {
16     // 截取字符串:从index到结束处
17     // - Parameter index: 开始索引
18     // - Returns: 子字符串
19     func subString(_ index: Int) -> String {
20         let theIndex = self.index(self.endIndex, offsetBy: index - self.count)
21         return String(self[theIndex..<endIndex])
22     }
23     
24     // 截取字符串:指定索引和字符数
25     // - begin: 开始截取处索引
26     // - count: 截取的字符数量
27     func subString(_ begin:Int,_ count:Int) -> String {
28         let start = self.index(self.startIndex, offsetBy: max(0, begin))
29         let end = self.index(self.startIndex, offsetBy:  min(self.count, begin + count))
30         return String(self[start..<end]) 
31     }
32 }
复制代码

点击:Playground测试

1 var sol = Solution()
2 print(sol.canWin("++++"))
3 //Print true

 

posted @   为敢技术  阅读(289)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示
哥伦布
09:09发布
哥伦布
09:09发布
3°
多云
东南风
3级
空气质量
相对湿度
47%
今天
中雨
3°/15°
周三
中雨
3°/13°
周四
小雪
-1°/6°