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 n-th sequence.
Note: The sequence of integers will be represented as a string.
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 n-th sequence.
Note: The sequence of integers will be represented as a string.
public String countAndSay(int n) {
if (n < 0)
return "";
// Go n-1 steps starting from the first integer "1"
String result = "1";
for (int i = 1; i < n; i++) {
// StringBuilder: a mutable sequence of characters similar to StringBuffer
// but with no guarantee of synchronization; recommended for most cases
StringBuilder builder = new StringBuilder();
int count = 1; // The number of appearances of the same digit
for (int j = 1; j < result.length(); j++) {
if (result.charAt(j) == result.charAt(j-1)) { // Same as the preceding digit
count++;
} else { // A different digit
builder.append(count); // Append the count of appearances of the character
builder.append(result.charAt(j-1)); // Append the character itself
count = 1; // Reset count
}
}
// The last digit and its count of appearances have not been included in builder
builder.append(count);
builder.append(result.charAt(result.length()-1));
// Get the next integer in the sequence
result = builder.toString();
}
// Out of loop; we arrive at the n-th integer
return result;
}
Read full article from LeetCode - Count and Say | Darren's Blog
No comments:
Post a Comment