Java solution


  • 0
    N

    The description was kind of misleading especially if you have seen a similar problem where you are just counting the numbers and outputting the answer whereas here you are finding the term of a sequence. It should say that in the title instead of "count and say" -- "Find the term of CountAndSay sequence".

    public class Solution {
    		   
        public String countAndSay(int n) {
    		        String str = "1";
    		        int j=1,cnt=1;
    		        while(j<n){
    					StringBuilder sb = new StringBuilder();
    					for (int i = 0; i < str.length(); i++) {
    						if  ((i+1)<str.length() && str.charAt(i) == str.charAt(i + 1)) {
    							cnt++;
    						} else {
    							sb.append(cnt);
    							sb.append(str.charAt(i));
    							cnt = 1;
    						}
    					}
    					if(cnt>1){
    						sb.append(cnt);
    						sb.append(str.charAt(str.length()-1));
    					}
    					str = sb.toString();
    					j++;
    			}
    					return str;
    		    }
    		    
    		}

Log in to reply
 

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