Lengthof Last Word Algorithm

The Length of Last Word Algorithm is a simple yet efficient algorithm used to determine the length of the last word in a given string. This algorithm is commonly asked in coding interviews as it tests the candidate's ability to manipulate strings and handle edge cases. The primary goal of the algorithm is to traverse the input string from the end and count the number of characters in the last word. A word is defined as a sequence of non-space characters, and the last word is the last such sequence of characters in the input string. The algorithm starts by initializing a counter variable to keep track of the length of the last word. Then, it iterates over the input string in reverse order, starting from the last character and moving towards the first character. The iteration stops when the first non-space character is encountered, and the counter is incremented for each subsequent non-space character until a space character is found. To handle edge cases like leading or trailing spaces, the algorithm should ignore any spaces encountered at the beginning of the reverse iteration. Once the iteration is complete, the counter variable will hold the length of the last word in the input string.
class Solution {
public:
    int lengthOfLastWord(const char *s) {
        int curr = 0;
        const char* p = s;
        while (*p != '\0') {
            if (*p == ' ') {
                p++;
            } else {
                curr = 0;
                while (*p != '\0' && *p != ' ') {
                    p++;
                    curr++;
                }
            }
        }
        return curr;
    }
};

LANGUAGE:

DARK MODE: