4 ms java solution, easy to understand. Although a little bit long


  • 0
    public static String countAndSay(int n) {
    		
    	StringBuilder result = new StringBuilder();
            if(n < 1){
                    return "";
            }
            if(n == 1) {
            	return "1";
            }
            else if(n == 2) {
        		return "11";
            }
            else {
            	String last = countAndSay(n-1);
            	char[] c = last.toCharArray();
            	int count =1;
            	for(int i = 0; i < c.length-1; i++) {
            		if(c[i] == c[i+1]) {
            			count += 1;
            		}
            		else if(c[i] != c[i+1] || i == c.length-2){
            			result.append(count).append(c[i]);
            			count = 1;
            		}
            	}
            	if(c[c.length-2] != c[c.length-1]) {
            		result.append("1").append(c[c.length-1]);
            	}
            	else {
            		result.append(count).append(c[c.length-2]);
            	}
            	return result.toString();
            }
            
        }
    

Log in to reply
 

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