|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 |
| -/** |
4 |
| - * 38. Count and Say |
5 |
| - * |
6 |
| - * The count-and-say sequence is the sequence of integers beginning as follows: |
7 |
| - 1, 11, 21, 1211, 111221, ... |
8 |
| -
|
9 |
| - 1 is read off as "one 1" or 11. |
10 |
| - 11 is read off as "two 1s" or 21. |
11 |
| - 21 is read off as "one 2, then one 1" or 1211. |
12 |
| - Given an integer n, generate the nth sequence. |
13 |
| -
|
14 |
| - Note: The sequence of integers will be represented as a string.*/ |
15 |
| - |
16 | 3 | public class _38 {
|
17 |
| - public static class Solution1 { |
18 |
| - public String countAndSay(int n) { |
19 |
| - StringBuilder curr = new StringBuilder("1"); |
20 |
| - StringBuilder prev; |
21 |
| - int count; |
22 |
| - char say; |
23 |
| - for (int i = 1; i < n; i++) { |
24 |
| - prev = curr; |
25 |
| - curr = new StringBuilder(); |
26 |
| - count = 1; |
27 |
| - say = prev.charAt(0); |
| 4 | + public static class Solution1 { |
| 5 | + public String countAndSay(int n) { |
| 6 | + StringBuilder curr = new StringBuilder("1"); |
| 7 | + StringBuilder prev; |
| 8 | + int count; |
| 9 | + char say; |
| 10 | + for (int i = 1; i < n; i++) { |
| 11 | + prev = curr; |
| 12 | + curr = new StringBuilder(); |
| 13 | + count = 1; |
| 14 | + say = prev.charAt(0); |
28 | 15 |
|
29 |
| - for (int j = 1, len = prev.length(); j < len; j++) { |
30 |
| - if (prev.charAt(j) != say) { |
31 |
| - curr.append(count).append(say); |
32 |
| - count = 1; |
33 |
| - say = prev.charAt(j); |
34 |
| - } else { |
35 |
| - count++; |
36 |
| - } |
| 16 | + for (int j = 1, len = prev.length(); j < len; j++) { |
| 17 | + if (prev.charAt(j) != say) { |
| 18 | + curr.append(count).append(say); |
| 19 | + count = 1; |
| 20 | + say = prev.charAt(j); |
| 21 | + } else { |
| 22 | + count++; |
| 23 | + } |
| 24 | + } |
| 25 | + curr.append(count).append(say); |
| 26 | + } |
| 27 | + return curr.toString(); |
37 | 28 | }
|
38 |
| - curr.append(count).append(say); |
39 |
| - } |
40 |
| - return curr.toString(); |
41 | 29 | }
|
42 |
| - } |
43 | 30 |
|
44 | 31 | }
|
0 commit comments