★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-adqbetwj-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
A magical string S consists of only '1' and '2' and obeys the following rules:git
The string S is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string Sitself.github
The first few elements of string S is the following: S = "1221121221221121122……"微信
If we group the consecutive '1's and '2's in S, it will be:app
1 22 11 2 1 22 1 22 11 2 11 22 ......spa
and the occurrences of '1's or '2's in each group are:code
1 2 2 1 1 2 1 2 2 1 2 2 ......htm
You can see that the occurrence sequence above is the S itself.blog
Given an integer N as input, return the number of '1's in the first N number in the magical string S.three
Note: N will not exceed 100,000.
Example 1:
Input: 6 Output: 3 Explanation: The first 6 elements of magical string S is "12211" and it contains three 1's, so return 3.
神奇的字符串 S 只包含 '1' 和 '2',並遵照如下規則:
字符串 S 是神奇的,由於串聯字符 '1' 和 '2' 的連續出現次數會生成字符串 S 自己。
字符串 S 的前幾個元素以下:S = 「1221121221221121122 ......」
若是咱們將 S 中連續的 1 和 2 進行分組,它將變成:
1 22 11 2 1 22 1 22 11 2 11 22 ......
而且每一個組中 '1' 或 '2' 的出現次數分別是:
1 2 2 1 1 2 1 2 2 1 2 2 ......
你能夠看到上面的出現次數就是 S 自己。
給定一個整數 N 做爲輸入,返回神奇字符串 S 中前 N 個數字中的 '1' 的數目。
注意:N 不會超過 100,000。
示例:
輸入:6 輸出:3 解釋:神奇字符串 S 的前 6 個元素是 「12211」,它包含三個 1,所以返回 3。
1 class Solution { 2 func magicalString(_ n: Int) -> Int { 3 if n <= 0 {return 0} 4 if n <= 3 {return 1} 5 var res:Int = 1 6 var head:Int = 2 7 var tail:Int = 3 8 var num:Int = 1 9 var v:[Int] = [1, 2, 2] 10 while(tail < n) 11 { 12 for i in 0..<v[head] 13 { 14 v.append(num) 15 if num == 1 && tail < n 16 { 17 res += 1 18 } 19 tail += 1 20 } 21 num ^= 3 22 head += 1 23 } 24 return res 25 } 26 }
124ms
1 class Solution { 2 func magicalString(_ n: Int) -> Int { 3 var sequence = [Int]() 4 sequence.append(contentsOf: [1,2,2]) 5 var groups = 2 6 var result = 1 7 if(n==0){return 0} 8 while sequence.count<n { 9 if(sequence[groups]==1){ 10 result += sequence.last! == 1 ? 0:1 11 sequence.append(sequence.last! == 1 ? 2:1) 12 groups+=1 13 }else{ 14 let temp = sequence.last! == 1 ? 2:1 15 sequence.append(contentsOf: [temp,temp]) 16 result += temp == 1 ? 2:0 17 groups+=1 18 } 19 } 20 if(sequence.count==n){return result}else{ 21 result -= sequence.last! == 1 ? 1:0 22 return result 23 } 24 } 25 }