# 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();
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/string/38.-count-and-say.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
