Simple Java Solution 96%


  • 0
    V

    Walk through the string and counting the character, once u see the different character, append the character and count , and reset the counter. Do this for as many times as the value of n starting from 2.

    public class Solution {
        
        
        public String counts(String s){
            StringBuilder sb = new StringBuilder();
            int count = 0 , i = 0,sl = s.length();
            char c ;
            while(i<sl){
                c = s.charAt(i);
                while(i<sl && c == s.charAt(i)){ i++;count++;}
                sb.append(count);
                sb.append(c);
                count = 0;
            }
            return sb.toString();
        }
        public String countAndSay(int n) {
            
            if(n ==0 || n<0 ) return null;
            String s = String.valueOf(1);
            if(n ==1 )return s;
            String res = s;
            
            for(int i=2;i<=n;i++){
               res = counts(res);   
            }
            return res;
        }
    }

Log in to reply
 

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