An easy to understand solution with 4ms


  • 0
    W
    public static String countAndSay(int n) {
        if(n==1) return "1";
        return countAndSay(countAndSay(n-1));
        }
    private static String countAndSay(String s){
    	StringBuilder sb =new StringBuilder();
    	char a = s.charAt(0);
    	int count=1;
    	for(int n=1;n<s.length();n++){
    		if(a==s.charAt(n)){
    			count++;
    		}
    		else {
    			sb.append(count);
    			sb.append(a);
    			a=s.charAt(n);
    			count=1;
    		}
    	}
    	sb.append(count);
    	sb.append(a);
    	return sb.toString();
    }
    

Log in to reply
 

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