[Swift]LeetCode481. 神奇字符串 | Magical String
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10348462.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
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: 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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了