Java solution


  • 0
    L
    public class Solution {
        public String countAndSay(int n) {
            String nStr = String.valueOf(1);
            int nums = n-1;
            
            while(nums>0){
                int times = 1;
                StringBuilder sb = new StringBuilder();
                int i = 0;
                int j = 1;
                while(j<nStr.length()){
                    while(nStr.charAt(i) == nStr.charAt(j)){
                        times++;
                        j++;
                        
                        if(j>=nStr.length()){
                           break;
                        }
                    }
      
                    sb.append(String.valueOf(times)+nStr.charAt(i));
    
                    times = 1;
                    i = j;
                    j++;
                }
                if(i<nStr.length()){
                    sb.append(String.valueOf(times)+nStr.charAt(i));
                }
                nStr = sb.toString();
                
                nums--;
            }
            
            return nStr;
        }
    }
    

Log in to reply
 

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