38. Count and Say
1. 1
2. 11
3. 21
4. 1211
5. 111221Input: 1
Output: "1"Input: 4
Output: "1211"解题要点:
class Solution {
public String countAndSay(int n) {
if(n == 1) return "1";
StringBuilder sb = new StringBuilder();
String s = countAndSay(n - 1) + "*";
int count = 1;
for(int i = 0; i < s.length() - 1; i++){
if(s.charAt(i) == s.charAt(i+1))
count++;
else{
sb.append(count);
sb.append(s.charAt(i));
count = 1;
}
}
return sb.toString();
}
}Last updated