C++ recursive with iterators


  • 0
    T

    Recursively generate string for n-1. Then left to right counting traversal.

    string countAndSay(int n)
    {
      if (n == 1) return "1";
    
      auto s = countAndSay(n-1);
      auto li = s.begin();
      auto ri = li; 
    
      string res;
      while (li != s.end()) {
        if (*li != *ri) {
          res.append(to_string(distance(li, ri))) += *li;
          li = ri; 
        }   
        ri++;
      }
      return res;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.