> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/string/38.-count-and-say.md).

# 38. Count and Say

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MfvQvKmcYsGZRZsbbvf%2F-MfvslYkntzmxMcMp8gL%2Fimage.png?alt=media\&token=989bf109-d5af-44d2-b4b4-7243c29b9068)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MfvQvKmcYsGZRZsbbvf%2F-MfvsophiROvSWt5Ih1r%2Fimage.png?alt=media\&token=f72d1673-e844-4dff-925e-f8dbd1c5c579)

time: O(n\*n/2) maybe?

space: O(n)

```java
class Solution {
    public String countAndSay(int n) {
        String res = "1";
        for (int i = 1 ; i < n; i++) {
            res = cal(res);
        }
        return res;
    }

    /*
 1.     1
 2.     11
 3.     21
 4.     1211
 5.     111221 
 6.     312211
 7.     13112221
 8.     1113213211
 9.     31131211131221
 10.   13211311123113112211

    */
    private String cal(String s) {
        int i = 0;
        StringBuilder sb = new StringBuilder();

        while (i < s.length()) {
            char temp = s.charAt(i);
            int count = 0;
            
            while (i < s.length() && s.charAt(i) == temp) {
                i++;
                count++;
            }
            sb.append(count);
            sb.append(temp);
        }
        return sb.toString();
    }
}
```
