java 4ms


  • 0
    W

    public class Solution {
    public String countAndSay(int n) {
    String b;
    if (n==1) return "1";
    else {
    b = countAndSay(n-1);
    return count(b);
    }
    }
    public String count(String b){
    StringBuilder a = new StringBuilder();
    char eql;
    int i = 0;
    int c = 0;
    while (i<b.length()){
    eql = b.charAt(i);
    while ( b.charAt(i) == eql){
    c++;
    i++;
    if (i==b.length()) break;
    }
    a.append(c).append(b.charAt(i-1));
    c = 0;
    }
    return a.toString();
    }
    }>! >! Spoiler


  • 0
    W
    public class Solution {
        public String countAndSay(int n) {
            String b;
            if (n==1) return "1";
            else {
                b = countAndSay(n-1);
                return count(b);
            }
        }
        public String count(String b){
            StringBuilder a = new StringBuilder();
            char eql;
            int i = 0;
            int c = 0;
            while (i<b.length()){
                eql = b.charAt(i);
                while ( b.charAt(i) == eql){
                    c++;
                    i++;
                    if (i==b.length()) break;
                }
                a.append(c).append(b.charAt(i-1));
                c = 0;
            }
            return a.toString();
        }
    }
    

Log in to reply
 

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