c# solution - easy to understand - iterate all possibilities


  • 0
    B
    public class Solution 
    {
        public int MagicalString(int n) 
        {
            if (n < 1) return 0;
            if (n == 1) return 1;
    
            var future = new StringBuilder("122");
            var present = new StringBuilder("12");
    
            int oneCount = 1;
    
            var futureCur  = future.Length - 1;
    
            while(futureCur < n - 1)
            {
                var presentCur = present.Length - 1;
                var presentNext = present.Length;
    
                if (future[futureCur] == '1' && present[presentCur] == '1')
                {
                    future.Append(2);
                    if(future[presentNext] == '2') future.Append(2);
                }
                else if (future[futureCur] == '1' && present[presentCur] == '2')
                {
                    future.Append(2);
                    if (future[presentNext] == '2') future.Append(2);
                }
                else if (future[futureCur] == '2' && present[presentCur] == '1')
                {
                    future.Append(1);
                    oneCount++;
                    if (future[presentNext] == '2') 
                    {
                        future.Append(1);
                        if (future.Length < n) oneCount++;
                    }
                }
                else if (future[futureCur] == '2' && present[presentCur] == '2')
                {
                    future.Append(1);
                    oneCount++;
                    if (future[presentNext] == '2') 
                    {
                        future.Append(1);
                        if (future.Length < n) oneCount++;
                    }
                }
    
                present.Append(future[presentCur + 1]);
    
                 futureCur  = future.Length - 1;
            }
    
            return oneCount;
        }
    }
    

Log in to reply
 

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