Simple C++ implementation without calling any library function


  • 0
    X

    pos tracks the beginning of current word.

    class Solution {
    public:
        int lengthOfLastWord(const char *s) {
            int len = 0;
            const char *pos;
            for (pos = s; *s; s++) {
                if (' ' == *s) {
                    if (s - pos > 0)
                        len = s - pos;
                    pos = s + 1;
                }
            }
            // last char not space
            if (s - pos > 0)
                len = s - pos;
    
            return len;
        }
    };

Log in to reply
 

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