★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-vksdrklj-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 twoconsecutive "++"
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 compute all possible states of the string after one valid move.github
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 []
.app
您正在和您的朋友玩如下翻轉游戲:給定一個僅包含這兩個字符的字符串:+和-,您和您的朋友輪流將兩個插入「++」翻轉爲「--」。遊戲結束時,一我的不能再作一個動做,所以另外一我的將是贏家。函數
寫一個函數來計算一次有效移動後字符串的全部可能狀態。spa
例如,給定s=「+++++」,移動一次後,它可能成爲如下狀態之一:code
[ "--++", "+--+", "++--"]
若是沒有有效的移動,請返回空列表[]。htm
Solution:blog
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 }