[Swift]LeetCode294. 翻轉游戲之 II $ Flip Game II

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-buzevrts-kv.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★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 two consecutive "++" into "--". The game ends when a person can no longer make a move and therefore the other person will be the winner.git

Write a function to determine if the starting player can guarantee a win.github

Example:算法

Input: 
Output: true 
Explanation: The starting player can guarantee a win by flipping the middle  to become .
s = "++++""++""+--+"

Follow up:
Derive your algorithm's runtime complexity.微信


您正在和您的朋友玩如下翻轉游戲:給定一個僅包含這兩個字符的字符串:+和-,您和您的朋友輪流將兩個連續的「++」翻轉爲「-」。遊戲結束時,一我的不能再作一個動做,所以另外一我的將是贏家。函數

寫一個函數來肯定首發球員是否能保證獲勝。測試

例子:spa

輸入:s = "++++"code

輸出:truehtm

說明:先手玩家能夠經過將中間「++」翻轉成「+--+」來保證獲勝。

跟進:

推導算法的運行時複雜性。


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
相關文章
相關標籤/搜索