-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path38.java
More file actions
36 lines (33 loc) · 1009 Bytes
/
Copy path38.java
File metadata and controls
36 lines (33 loc) · 1009 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public String countAndSay(int n) {
String result = "1";
for (int i = 1;i < n;i++) {
result = countAndSay(result);
}
return result;
}
public String countAndSay(String str) {
int count = 0;
StringBuilder result = new StringBuilder();
char lastChar = '\0';
char currChar;
for (int i = 0; i < str.length();i++) {
currChar = str.charAt(i);
if (lastChar == '\0') {
lastChar = currChar;
count++;
} else if (currChar == lastChar) {
count++;
} else if (currChar != lastChar) {
result.append(count).append(lastChar);
lastChar = currChar;
count = 1;
}
}
result.append(count).append(lastChar);
return result.toString();
}
public static void main(String[] args) {
System.out.println(new Solution().countAndSay(5));
}
}