Java Solution Easy understand


  • 1
    
    public class Solution {
        public int magicalString(int n) {
            if(n==0) return 0;
            StringBuilder sb=new StringBuilder("122");
            int distcnt=2;
            int ret=1;
            while(sb.length()<n)
            {
                char ch=sb.charAt(distcnt);
                char prev=sb.charAt(sb.length()-1);
                if(ch=='1')
                {
                    if(prev=='1') sb.append("2");
                    else{ sb.append("1");  ret++;}
                }
                else
                {
                    if(prev=='1') {sb.append("22");}
                    else{
                        sb.append("11");  
                       ret= sb.length()==n+1 ? ret+1:ret+2;
     
                    }
                }
                distcnt++;
            }
           // if(sb.length()==n+1&&sb.charAt(sb.length()-1)=='1') return ret-1;
            return ret;
        }
    }
    

Log in to reply
 

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