My sample java solution


  • 0
    I

    It is straightforward looping , counting, concatenate, but without unnecessary checks..
    The Idea is, we say the count of every similar sequential numbers
    ex. 111221 : we have 3 ones(31) , 2 twos(22) , 1 one(11) = 312211

       public static String countAndSay(int n) {
    		String current=new String("1");
    		StringBuilder result=new StringBuilder("1");
    		int count=0;
    		for(int i=1;i<n;i++) {
    			result=new StringBuilder();
    			for(int j=0;j<current.length();j++) {
    				count++;
    				if(j==current.length()-1 || current.charAt(j)!=current.charAt(j+1) ) {
    					result.append(count+""+current.charAt(j));
    					count=0;
    				}
    			}
    			current=result.toString();
    		}
    		return result.toString();
    	}

Log in to reply
 

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