DEV Community

codechunker
codechunker

Posted on • Edited on • Originally published at Medium

What you need to know about Leetcode’s Count and Say: My thought process as a beginner.

This is another Leetcode Problem: You are given an integer to generate the nth term of its count and say.The count and say is a way of reading off digits from the previous member. So 1 would read as “One 1” or 11 and 11 would read as “Two 1s” or 21 etc.

ALGORITHM

1.Get the first character of the string. This would serve as the previous;
2.Loop through every other character (i.e from the next character after step 1). This would serve as the next character.
3.Compare if step 1 and 2 (previous and next) are equal.
4.If they are equal, increment the global counter.
5.If they are not equal, append the current value of global counter and the previous character (in that order) into a global result StringBuilder. The previous character now becomes the current next character (previous = next). Then reset global counter (count = 1).
6.Outside the loop, append the global counter and previous to the global result.This is majorly for edge cases.

MY CODE

class Solution {
    public String countAndSay(int n) {
          if (n == 1)
            return "1";
        else {
            return doCounting(countAndSay(n - 1));
        }
    }

    private String doCounting(String value) {
        int length = value.length();
        int count = 1;
        StringBuilder result = new StringBuilder();
        int i;
        char previous = value.charAt(0);//initial
        for (i  = 1; i < length; i++) {
            char next = value.charAt(i);
            if (previous == next) {
                count++;
            }else {
                result.append(count).append(previous);
                previous = next;
                count = 1;//reset
            }
        }
        result.append(count).append(previous);

        return result.toString();
    }
}

OUTCOME
outcome image

IMPROVEMENT
At first, the solution was a bit slower so I had to scan through to look for a way to make my solution a bit faster. Found out where I got it wrong: For every loop, I was calling value.length(). This should be reusable, so I initialized it to a variable. Did the same thing for charAt(i).
After the cleanups, I got the above scores, which I feel is very OK.

LESSONS
Always initialize some library functions to variable to prevent calling it multiple times e.g, value.length(), value.charAt(i) etc. I’m sure you get the point. This also applies to Object creations or instances.

CONCLUSION
I hope you keep solving problems by chunking them. Please leave a comment, correction or suggestion (I'd really love that). Thank you.

Top comments (0)