A simple and faster iterative method


  • 0
    L

    If you are not able to figure out how to proceed, look at the string. If you start with "1" and look from left to right, you would realize that you would start counting a number left to right till : 1. either another number shows up , or 2. the string ends. Use this logic to read say "211". You first read 2 with a count of 1 and then read 2 1s. Here is the code:

        public String countAndSay(int n) {
            /**
                “1211” -> "111221
            */
            String s = "1";
            for(int i=2;i<=n;i++) {
                StringBuilder builder = new StringBuilder();
                int j=0;
                while(j<s.length()) {
                    int count=1;
                    char c = s.charAt(j);
                    while(j+1<s.length() && s.charAt(j+1)==c) {
                        count++;
                        j++;
                    }
                    builder.append(count);
                    builder.append(c);
                    j++;
                }
                s = builder.toString();
            }
            
            return s;
        }
    

Log in to reply
 

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