38. Count and Say

 1 class Solution {
 2     public String countAndSay(int n) {
 3         String str = "1";
 4         if(n == 1) return str;
 5         return helper(str, n - 1);
 6     
 7         
 8     }
 9     
10     public String helper(String str, int n) {
11         if(n == 0) return str;
12         String res = "";
13         HashMap<Character, Integer> map = new HashMap<>();
14         map.put(str.charAt(0), 1);
15         for(int i = 0; i < str.length(); i++) {
16             if(i != str.length()-1) {
17                 if(str.charAt(i) == str.charAt(i+1)) {
18                     map.put(str.charAt(i+1), map.get(str.charAt(i))+1);
19                 }else {
20                     res = res + map.get(str.charAt(i)) + str.charAt(i);
21                     map.put(str.charAt(i+1), 1);
22                 }
23             }else {
24                 res = res + map.get(str.charAt(i)) + str.charAt(i);
25             }
26         }
27         return helper(res, n - 1);
28     }
29 }

 

posted @ 2018-09-10 11:14  jasoncool1  阅读(117)  评论(0编辑  收藏  举报