题目描述(简单难度)
示例如下:
-
1
-
11
-
21
-
1211
-
111221
初始值第一行是 1。
第二行读第一行,1 个 1,去掉个字,所以第二行就是 11。
第三行读第二行,2 个 1,去掉个字,所以第三行就是 21。
第四行读第三行,1 个 2,1 个 1,去掉所有个字,所以第四行就是 1211。
第五行读第四行,1 个 1,1 个 2,2 个 1,去掉所有个字,所以第五航就是 111221。
第六行读第五行,3 个 1,2 个 2,1 个 1,去掉所以个字,所以第六行就是 312211。
然后题目要求输入 1 - 30 的任意行数,输出该行是啥。
解法
两两字符之间依次进行对比,如果相邻字符相等,那么count+1;否则把后面字符赋值给前面字符,重复之前的操作。
Java
public String countAndSay(int n) {
String pre ="1";
for(int i = 1;i < n;i++){
char first = pre.charAt(0);
StringBuilder temp = new StringBuilder();
int count = 1;
for(int j = 1;j<pre.length();j++){
char second = pre.charAt(j);
if(first == second){
count++;
}else{
temp.append(count).append(first);
count = 1;
first = second;
}
}
temp.append(count).append(first);
pre=temp.toString();
}
return pre;
}
public static void main(String args[]) {
int n=5;
String ans=countAndSay(n);
System.out.println(ans);
}
}
Python
class Solution(object):
def countAndSay(self, n):
pre ="1"
for i in range(1,n):
first = pre[0]
temp = []
count = 1
for j in range(1,len(pre)):
second = pre[j]
if first == second:
count+=1
else:
temp.append(count)
temp.append(first)
count = 1
first = second
temp.append(count)
temp.append(first)
new_temp = [str(x) for x in temp]
pre="".join(new_temp)
return pre
参考文献
- https://blog.csdn.net/google19890102/article/details/80932546