Leetcode38. Count and Say Java实现

先尝试了一波类的实例变量和构造器以及静态变量和静态初始化块,分别:

 1 class Solution {
 2     private String[] countsay = new String[30];
 3     public Solution(){
 4         countsay[0] = "1";
 5         for(int i=1;i<30;i++){
 6             StringBuilder sb = new StringBuilder();
 7             int count = 1;char cur = countsay[i-1].charAt(0);
 8             for(int j=1;j<countsay[i-1].length();j++){
 9                 if(cur==countsay[i-1].charAt(j)){
10                     count++;
11                 }else{
12                     sb.append(count);
13                     sb.append(cur);
14                     count=1;cur=countsay[i-1].charAt(j);
15                 }           
16             }
17             sb.append(count);
18             sb.append(cur);
19             countsay[i]=sb.toString();
20         }
21     }
22     public String countAndSay(int n) {
23         return countsay[n-1];
24     }
25 }

14ms,22.77%。

 1 class Solution {
 2     private static String[] countsay = new String[30];
 3     static{
 4         countsay[0] = "1";
 5         for(int i=1;i<30;i++){
 6             StringBuilder sb = new StringBuilder();
 7             int count = 1;char cur = countsay[i-1].charAt(0);
 8             for(int j=1;j<countsay[i-1].length();j++){
 9                 if(cur==countsay[i-1].charAt(j)){
10                     count++;
11                 }else{
12                     sb.append(count);
13                     sb.append(cur);
14                     count=1;cur=countsay[i-1].charAt(j);
15                 }           
16             }
17             sb.append(count);
18             sb.append(cur);
19             countsay[i]=sb.toString();
20         }
21     }
22     public String countAndSay(int n) {
23         return countsay[n-1];
24     }
25 }

16ms 19.91%

静态初始化块比实例变量还慢,有点出乎意料。然后是正常操作:

class Solution {
    public String countAndSay(int n) {
        String[] countsay = new String[n];
        countsay[0] = "1";
        for(int i=1;i<n;i++){
            StringBuilder sb = new StringBuilder();
            int count = 1;char cur = countsay[i-1].charAt(0);
            for(int j=1;j<countsay[i-1].length();j++){
                if(cur==countsay[i-1].charAt(j)){
                    count++;
                }else{
                    sb.append(count);
                    sb.append(cur);
                    count=1;cur=countsay[i-1].charAt(j);
                }           
            }
            sb.append(count);
            sb.append(cur);
            countsay[i]=sb.toString();
        }
        return countsay[n-1];
    }
}

5ms,41.53%。 

看了1ms答案,思路和我基本一致,只是换成了递归调用,少存了一个countsay数组。个人最优解就可以了。

posted @ 2018-12-26 21:46  大胖子球花  阅读(111)  评论(0)    收藏  举报