Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c06923c

Browse files
committed
Count and say done
1 parent fd79157 commit c06923c

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package com.leetcode.strings;
2+
3+
/**
4+
* Problem: https://leetcode.com/problems/count-and-say/
5+
*
6+
* @author rampatra
7+
* @since 2019年04月20日
8+
*/
9+
public class CountAndSay {
10+
11+
/**
12+
* Time complexity:
13+
* Runtime: <a href="https://leetcode.com/submissions/detail/223728660/">1 ms</a>.
14+
*
15+
* @param n
16+
* @return
17+
*/
18+
public static String countAndSay(int n) {
19+
if (n == 1) return "1";
20+
21+
String s = countAndSay(n - 1);
22+
StringBuilder sb = new StringBuilder();
23+
int count = 0;
24+
25+
for (int i = 0; i < s.length(); i++) {
26+
count++;
27+
28+
if (i + 1 >= s.length() || s.charAt(i) != s.charAt(i + 1)) {
29+
sb.append(count);
30+
sb.append(s.charAt(i));
31+
count = 0;
32+
}
33+
}
34+
35+
return sb.toString();
36+
}
37+
38+
public static void main(String[] args) {
39+
System.out.println(countAndSay(1));
40+
System.out.println(countAndSay(2));
41+
System.out.println(countAndSay(3));
42+
System.out.println(countAndSay(4));
43+
System.out.println(countAndSay(5));
44+
System.out.println(countAndSay(6));
45+
System.out.println(countAndSay(10));
46+
}
47+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /