File tree 1 file changed +47
-0
lines changed
src/main/java/com/leetcode/strings
1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments