Java Solution With Some Points Explanation


  • 0
    S

    The are two tricky points in this program in my point of view. For one, in the while loop we can't just make the statement words.charAt(j++) since every branch j will auto increment. For another, in the else branch inside while loop, the count should be refresh to 0.

       public class Solution {
            public String countAndSay(int n) {
                StringBuilder sb = new StringBuilder();
                if(n<=0) return sb.toString(); 
                StringBuilder words = new StringBuilder("1");
                for(int i=1; i<n; i++){
                    sb.setLength(0);
                    int j=0;
                    int count = 0;
                    char c = words.charAt(0);
                    while(j<words.length()){
                        if(words.charAt(j)==c){
                            count++;
                            j++;
                        }
                        else{
                            sb.append(count).append(c);
                            c = words.charAt(j);
                            count = 0;
                        }
                    }
                    sb.append(count).append(c);
                    words.setLength(0);
                    words.append(sb);
                }
                return words.toString();
            }
        }

Log in to reply
 

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