Title:Count and Say 38
Difficulty:Easy
原题leetcode地址:https://leetcode.com/problems/count-and-say/
1. 定义变量count,如果相邻的来给你个数相等,那么count++。否则将count和这个数存放,注意最后一个数
时间复杂度:O(n^2),嵌套for循环。
空间复杂度:O(1),没有申请额外的空间。
/**
* 定义变量count,如果相邻的来给你个数相等,那么count++。否则将count和这个数存放,注意最后一个数,不要遗落
* @param n
* @return
*/
public static String countAndSay(int n) {
if (n < 1) {
return null;
}
String res = "1";
for (int i = 2; i <= n; i++) {
res = countSay(res);
}
return res;
}
private static String countSay(String res) {
StringBuilder sb = new StringBuilder();
int count = 1;
for (int i = 1; i < res.length(); i++) {
if (res.charAt(i) == res.charAt(i - 1)) {
count++;
}
else {
sb.append(count);
sb.append(res.charAt(i - 1));
count = 1;
}
}
sb.append(count);
sb.append(res.charAt(res.length() - 1));
return sb.toString();
}