My accepted c++ solution


  • 0
    P

    Just for a record.
    STL:list and STL::string are used as containers.
    When doing output, string copy, string.append(), string.erase() are used.

    #include <cstdio>
    #include <cstdint>
    #include <string>
    #include <list>
    #include <iostream>
    using namespace std;
    
    struct node{
       uint32_t startpos;
       size_t len;
    };
    class Solution{
    public:
       void reverseWords(string & s)
       {
          if (s.empty())
          {
             s = "";
             return;
          }
          //analyze s into a list of nodes:()
          //iterate the list from the end. or reverse the list.
          //print the list.
          uint32_t startpos = 0;
          size_t sz = 0;
          for (char c : s)
          {
             //printf("%c", c);
             if (IsSpacing(c))
             {
                if (sz != 0)
                {
                   node nd;
                   nd.startpos = startpos;
                   nd.len = sz;
                   startpos += sz;
                   sz = 0;
                   m_list.push_front(nd);
                }
                startpos++;
             }
             else
             {
                sz++;
             }
          }
          if (sz != 0)
          {
             m_list.push_front(node{ startpos, sz });
          }
          if (!m_list.empty()){
             printReversedWords(s);
          }
          else
          {
             s = "";
          }
          clear();
       }
    
       void printReversedWords(string& s)
       {
          string r;
          for (list<node>::const_iterator it = m_list.begin(); it != m_list.end(); it++)
          {
             r.append(s, (*it).startpos, (*it).len);
             r.append(" ");
          }
          r.erase(r.end()-1);
          s = r;
          cout << s;
       }
       bool IsSpacing(const char &c)
       {
          return c == ' ' || c == '  ' || c == '\n' || c == '\r';
       }
       void clear()
       {
          m_list.clear();
       }
       list<node> m_list;
    };

Log in to reply
 

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