Java 4ms Solution


  • 0
    S
     public String countAndSay(int n) {
        if(n<1)
            return "1";
        
        //initialize result string
        String str = "1";
        for(int i=2; i<=n; i++){
            StringBuilder sb = new StringBuilder();
            char[] chars = str.toCharArray();
            int count=1;
            for(int j=1; j<chars.length; j++){
                if(chars[j]==chars[j-1]){
                    count++;
                    continue;
                }else{
                    sb.append(count);
                    sb.append(chars[j-1]);
                    count=1;
                }
            }
            
            //don't forget the last character
            sb.append(count);
            sb.append(chars[chars.length-1]);
            str = sb.toString();
        }
    
        return str;
    }

Log in to reply
 

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