38. Count and Say — LeetCode Solution

1.     1
2. 11
3. 21
4. 1211
5. 111221
Input: 1
Output: "1"
Explanation: This is the base case.
Input: 4
Output: "1211"
Explanation: For n = 3 the term was "21" in which we have two groups "2" and "1", "2" can be read as "12" which means frequency = 1 and value = 2, the same way "1" is read as "11", so the answer is the concatenation of "12" and "11" which is "1211".
class Solution {
public String countAndSay(int n) {
if (n<=0) {
return null;
}
String result = "1";
int i=1;
while (i++ < n) {
StringBuilder sb = new StringBuilder();
int count = 1;
for (int j = 1; j<result.length(); j++) {
if(result.charAt(j) == result.charAt(j-1)) {
count++;
} else {
sb.append(count);
sb.append(result.charAt(j-1));
count = 1;
}
}
sb.append(count);
sb.append(result.charAt(result.length()-1));
result = sb.toString();
}

return result;
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store