Now use stringbuilder, it's accepted


  • 0
    Z
    Re: [Can anyone tell me why I got TLE](it seems time is O(n))
        public class Solution {
        public int magicalString(int n){
        int count = 0;
        StringBuilder res = new StringBuilder();
        res.append(122);
        int index = 2;
        while(res.length() <= n){
            char c = res.charAt(index);
            int len = res.length();
            if(c == '1'){
                if(res.charAt(len - 1) == '1') res.append(2);
                if(res.charAt(len - 1) == '2') res.append(1);
            }
            else if(c == '2'){
                    if(res.charAt(len - 1) == '1') res.append(22);
                    if(res.charAt(len - 1) == '2') res.append(11);
            }
            index++;
        }
        for(int i = 0; i < n; i++){
            if(res.charAt(i) == '1') count++;
        }
        return count;
    }
    

    }


  • 0
    S

    Yo, i was using String and was getting TLE everytime. Realized the importance of string pool in java here.


Log in to reply
 

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