首页 > 其他分享 >481. 神奇字符串

481. 神奇字符串

时间:2022-10-31 10:56:33浏览次数:71  
标签:11 22 int 字符串 481 神奇

481. 神奇字符串

神奇字符串 s 仅由 '1' 和 '2' 组成,并需要遵守下面的规则:

  • 神奇字符串 s 的神奇之处在于,串联字符串中 '1' 和 '2' 的连续出现次数可以生成该字符串。

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 的数目。

循环模拟

class Solution {
public:
    string res;
    vector<int>cnt;

    int magicalString(int n) {
        res="122";
        for(int i=0;i<res.size();i++)
            cnt.push_back(res[i]-'0');

        int idx=2;
        while(res.size()<n){
            char temp;
            int oldsize=res.size();
            if(res[oldsize-1]=='1')
                temp='2';
            else
                temp='1';
            for(int i=0;i<cnt[idx];i++){
                res+=temp;
            }
            for(int i=oldsize;i<res.size();i++){
                cnt.push_back(res[i]-'0');
            }
            idx++;
        }
        int nn=0;
        for(int i=0;i<n;i++)
            if(res[i]=='1')
                nn++;
        // for(int i=0;i<res.size();i++){
        //     cout<<res[i]<<" ";
        // }
        // cout<<endl;
        // for(int i=0;i<cnt.size();i++)
        //     cout<<cnt[i]<<" ";
        return nn;
    }
};

标签:11,22,int,字符串,481,神奇
From: https://www.cnblogs.com/SkyDusty/p/16843560.html

相关文章