A EASY problem, just for accomplish today's task.
Already late again
And spend too much time, so I am disappointed.
DESCRIPTION:
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.
ANALYSIS:
Big problems with index dealing.
SOLUTION:
public static String countAndSay(int n) {
String string="1";
for(int i=1;i<n;i++){
if(string.length()==1){
string=1+string;
}else{
char d=string.charAt(0);
int count=1;
String tempString="";
for(int j=1;j<string.length();j++){
if(j==string.length()-1&&string.charAt(j)==string.charAt(j-1)){
count++;
tempString=tempString+count+d;
}else if(j==string.length()-1&&string.charAt(j)!=string.charAt(j-1)){
tempString=tempString+count+d+1+string.charAt(j);
}else if(string.charAt(j)==string.charAt(j-1)){
count++;
}else{
tempString=tempString+count+d;
d=string.charAt(j);
count=1;
}
}
string=tempString;
}
}
return string;
}
public static String countAndSayTop(int n) {
StringBuilder curr=new StringBuilder("1");
StringBuilder prev;
int count;
char say;
for (int i=1;i<n;i++){
prev=curr;
curr=new StringBuilder();
count=1;
say=prev.charAt(0);
for (int j=1,len=prev.length();j<len;j++){
if (prev.charAt(j)!=say){
curr.append(count).append(say);
count=1;
say=prev.charAt(j);
}
else count++;
}
curr.append(count).append(say);
}
return curr.toString();
}
网友评论