Java code using recursion


  • 0

    public String countAndSay(int n) {
    if (n == 1) return "1";
    String s = countAndSay(n-1);
    StringBuilder result = new StringBuilder();
    int i = 0, count = 0;
    while (i < s.length()) {
    count = i;
    while (i < s.length() - 1 && s.charAt(i+1) == s.charAt(i)) i++;
    result.append(i - count + 1).append(s.charAt(i++));
    }
    return result.toString();
    }


Log in to reply
 

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