Easy to understand java code.


  • 0
    G

    I think the main part of this problem is that you should use a StringBuilder for appending strings. Otherwise, if you use "somestring1" + "somestring2", it may exceed the time limit.

    public class Solution {

    public String countAndSay(int n) {
        String nums = "1";
        while(n > 1){
            nums = sayIt(nums);
            n--;
        }
        return nums;
    }
    
    public String sayIt(String num){
        if(num == null || num.length() == 0){
            return "";
        }
        StringBuilder result = new StringBuilder();
        char cur = num.charAt(0);
        int count = 1;
        for(int i = 1; i < num.length(); i++){
            if(cur == num.charAt(i)){
                count++;
            }
            else{
                result.append(count);
                result.append(cur);
                cur = num.charAt(i);
                count = 1;
            }
        }
        result.append(count);
        result.append(cur);
        
        return result.toString();
    }
    

    }


Log in to reply
 

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