1. 程式人生 > >[leetcode]38. Count and Say

[leetcode]38. Count and Say

健身完回來狀態不好,先做個easy吧
這個破題的decription有歧義吧,簡直了。

Solution 1: 沒什麼技術含量的遍歷

每執行一個count的時間複雜度是m(就是這一遍的長度),一共執行了n次這樣的count,m又是一個增長的量。但是我不知道m的增長速率。我覺得時間複雜度肯定在O(n*n)以上

class Solution {
    public String countAndSay(int n) {
        String res="1";
        int i=0;
       for(i=1;i<n;i++){
           res=count(res);
       }
        
        return res;
    }
    
    private String count(String s){
        
        int i=0;
        int len=s.length();
        
        String part="";
      
         while(i<len){
           
           int j=i;
           while(j<len&&s.charAt(j)==s.charAt(i)){
               j++;
           }
           int count=j-i;
           part+=String.valueOf(count);
           part+=s.charAt(i);
           
           i=j;
           
       }
        
       return part;
    }
}