前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 111221, ...
1
is read off as "one 1"
or 11
.
11
is read off as "two 1s"
or 21
.
21
is read off as "one 2
, then one 1"
or 1211
.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
这个题目也没啥好说的,首先推几个看有没有什么规律,如果有规律那就是O(1)的时间得到结果,否则就只能把所有的都求出来再输出。当然还可以先存一部分值。感觉没什么意义。 Your runtime beats 63.18% of java submissions.public class Solution {
public String countAndSay(int n) {
String input = "1";
while(n > 1){
input=generateNext(input);
n--;
}
return input;
}
String generateNext(String s){
if(s.length() == 1) return "1" + s;
int times = 1;
StringBuffer sb = new StringBuffer("");
char current = s.charAt(0);
for(int i = 1 ; i < s.length() ; i ++){
if(s.charAt(i) == current) times ++;
else{ sb.append(times);sb.append(current);current = s.charAt(i);times = 1;}
}
sb.append(times);
sb.append(current);
return sb.toString();
}
}