-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcount_say.java
More file actions
45 lines (44 loc) · 1.16 KB
/
count_say.java
File metadata and controls
45 lines (44 loc) · 1.16 KB
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
37
38
39
40
41
42
43
44
45
public class Solution {
public String countAndSay(int n) {
// Start typing your Java solution below
// DO NOT write main() function
if(n==1) return "1";
String pre="1",r="";
while(n>1) {
r="";
for(int i=0;i<pre.length();) {
int j=i+1,c=1;
while(j<pre.length()&&pre.charAt(j)==pre.charAt(j-1)) {
c++; j++;
}
i=j;
r+=c+""+pre.charAt(j-1);
}
pre=r;
n--;
}
return r;
}
}
public class Solution {
public String countAndSay(int n) {
// Start typing your Java solution below
// DO NOT write main() function
if(n==1) return "1";
String pre="1",r="";
while(n>1) {
r="";
for(int i=0;i<pre.length();) {
int j=i,c=1;
while(j<pre.length()-1&&pre.charAt(j)==pre.charAt(j+1)) {
c++; j++;
}
i=j+1;
r+=c+pre.substring(j,j+1);
}
pre=r;
n--;
}
return r;
}
}