38 Count and Say
he count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1is read off as"one 1"or11.11is read off as"two 1s"or21.21is read off as"one 2, thenone 1"or1211.
Given an integern, generate thenthterm of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input:
1
Output:
"1"
Example 2:
Input:
4
Output:
"1211"
Solution)
class Solution {
public String countAndSay(int n) {
if (n <= 0) return "";
String s = "1";
for (int i = 1; i < n; i++) {
StringBuffer sb = new StringBuffer();
int count = 1;
for (int j = 0; j < s.length(); j++) {
if (j < s.length()-1) {
if (s.charAt(j) == s.charAt(j+1)) count++;
else {
sb.append(String.valueOf(count)+s.charAt(j));
count = 1;
}
} else
sb.append(String.valueOf(count)+s.charAt(j));
}
s = sb.toString();
}
return s;
}
}
public class Solution {
public String countAndSay(int n) {
String s = "1";
for (int i = 1; i < n; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 1, count = 1; j <= s.length(); j++) {
if (j == s.length() || s.charAt(j - 1) != s.charAt(j)) {
sb.append(count);
sb.append(s.charAt(j - 1));
count = 1;
} else count++;
}
s = sb.toString();
}
return s;
}
}