C++ Code - Keep Track of Spaces and Ending of String


  • 0
    R

    Loop through the string keeping track of the index where you either saw a space or have reached the ending of the string. When you have both indexes (the starting and end positions for the current word), reverse the word and continue on.

    class Solution {
    public:
        void reverse(string & s, int beg, int end) {
            for(; beg < end; beg++, end--) {
                char temp = s[beg];
                s[beg] = s[end];
                s[end] = temp;
            }
        }
    
        string reverseWords(string & s) {
            if(s.empty()) return s;
            int beg = 0;
            int end = 0;
            int traveled = 0;
            
            for(int i = 0; i <= s.length(); i++) {
                if(isspace(s[i]) || i == s.length()) {
                    end = i - 1;
                    beg = i - traveled;
                    reverse(s, beg, end);
                    traveled = 0;
                } else {
                    traveled++;
                }
            }
            return s;
        }
    };
    

Log in to reply
 

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