C++_AC_two pointers_9ms_74.78%


  • 0

    Method: use the original string to generate the following string.

    class Solution {
    public:
    int magicalString(int n) {
        if(n <= 0) return 0;
        string s = "1";
        int i = 0, j = 0;
        int count = 0;
        while(i < n){
            if(s[j] == '1'){
                count++;
                char tmp = s[i] == '1' ? '2' : '1';
                s += tmp;
                i++;
            }else{//s[j] == '2'
                char tmp = s[i++];
                s += tmp;
                s += s[i++] == '1' ? '2' : '1';
            }
            j++;
        }
        while(j < n){if(s[j++] == '1') count++;}
        return count;
    }
    };
    

    0_1484430314501_WechatIMG64.jpeg


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.