A magical string S consists of only ‘1‘ and ‘2‘ and obeys the following rules:
The string S is magical because concatenating the number of contiguous occurrences of characters ‘1‘ and ‘2‘ generates the string Sitself.
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:
1 22 11 2 1 22 1 22 11 2 11 22 ......
and the occurrences of ‘1‘s or ‘2‘s in each group are:
1 2 2 1 1 2 1 2 2 1 2 2 ......
You can see that the occurrence sequence above is the S itself.
Given an integer N as input,return the number of ‘1‘s in the first N number in the magical string S.
Note: N will not exceed 100,000.
Example 1:
input: 6Output: 3Explanation: 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。Runtime: 20 ms Memory Usage: 10.1 MB
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 < n16 {17 res += 118 }19 tail += 120 }21 num ^= 322 head += 123 }24 return res25 }26 }
124ms
1 class Solution { 2 func magicalString(_ n: Int) -> Int { 3 var sequence = [Int]() 4 sequence.append(contentsOf: [1,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:111 sequence.append(sequence.last! == 1 ? 2:1)12 groups+=113 }else{14 let temp = sequence.last! == 1 ? 2:115 sequence.append(contentsOf: [temp,temp])16 result += temp == 1 ? 2:017 groups+=118 }19 }20 if(sequence.count==n){return result}else{21 result -= sequence.last! == 1 ? 1:022 return result23 }24 }25 }总结
以上是内存溢出为你收集整理的[Swift]LeetCode481. 神奇字符串 | Magical String全部内容,希望文章能够帮你解决[Swift]LeetCode481. 神奇字符串 | Magical String所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)