题目:
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.
题解:count occurrence of each type of character and make a new string: count1type1count2type2.....
C++版:
class Solution {
public:
string countAndSay(int n) {
if(n == 1)
return "1";
int i = 1;
string start = "1";
while(i < n) {
string end = "";
string result = "";
int j = 0;
while(j < start.length()) {
char c = start[j];
end += c;
j += 1;
int count = 1;
while(j < start.length() && start[j] == c) {
count++;
j++;
}
end = to_string(count) + end;
result += end;
end = "";
}
start = result;
i++;
}
return start;
}
};
Java版:
public class Solution {
public String countAndSay(int n) {
if(n == 1)
return "1";
StringBuffer start = new StringBuffer();
StringBuffer end = new StringBuffer();
StringBuffer result = new StringBuffer();
start.append("1");
int i = 1;
while(i < n) {
end.delete(0, end.length());
result.delete(0, result.length());
int j = 0;
while(j < start.length()) {
char c = start.charAt(j);
end.append(c);
int count = 1;
j++;
while(j < start.length() && start.charAt(j) == c) {
count++;
j++;
}
end.insert(0, Integer.toString(count));
result.append(end.toString());
end.delete(0, end.length());
}
start.delete(0, start.length());
start.append(result.toString());
i++;
}
return start.toString();
}
}
Python版:
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
if n == 1:
return "1"
i = 1
start = "1"
while i < n:
j = 0
end = ""
result = ""
while j < len(start):
cur = start[j]
end += cur
count = 1
j += 1
while j < len(start) and start[j] == cur:
count += 1
j += 1
end = str(count) + end
result += end
end = ""
start = result
i += 1
return start