g0001_0100.s0038_count_and_say.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java Show documentation
Show all versions of leetcode-in-java Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0001_0100.s0038_count_and_say;
// #Medium #Top_Interview_Questions #String #2022_02_18_Time_3_ms_(84.24%)_Space_41.7_MB_(38.69%)
public class Solution {
public String countAndSay(int n) {
if (n == 1) {
return "1";
}
StringBuilder res = new StringBuilder();
String prev = countAndSay(n - 1);
int count = 1;
for (int i = 1; i < prev.length(); i++) {
if (prev.charAt(i) == prev.charAt(i - 1)) {
count++;
} else {
res.append(count).append(prev.charAt(i - 1));
count = 1;
}
}
res.append(count).append(prev.charAt(prev.length() - 1));
return res.toString();
}
}