当前位置:网站首页>leetcode. 38 --- appearance series

leetcode. 38 --- appearance series

2022-06-10 06:57:00 _ End, broken chord

Look-and-say sequence

 Insert picture description here

Answer key : Here is the reference

Dynamic diagram demonstration :

 Insert picture description here

The code is as follows :

class Solution {
    
public:
    string countAndSay(int n) {
    
        string res = "1";
        if(n == 1) return res;//n=1 Go straight back to 
        for(int i = 1;i < n;i++){
    
            string tmp;
           int l = 0, r = 0;// Double pointer to find duplicate elements 
           while(r < res.size()){
         
               while(r < res.size() && res[r] == res[l]) r++;// equal r Just keep going right 
               tmp += to_string(r - l) + res[l]; // Splice up 
               l = r;// to update l To r The location of 
           }
          res = tmp;
        }
        return res;
    }
};

Time complexity :O(n^2)
Spatial complexity ;O(1)

原网站

版权声明
本文为[_ End, broken chord]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206100646268247.html