Most Simple C++ Solution (With Split-like feature of Python)

  • 0

    This solution uses all inbuilt methods of cpp to make life simple.

    First being strtok which takes char* as input and splits it with the delimiter we provide Check the Method here

    Next we need to convert our string to char* so we use .c_str() function. However, it porivdes const char* hence we use strdup().

    class Solution {
        int lengthOfLastWord(string s) {
            int ans = 0;
            char *token = strtok(strdup(s.c_str()), " "); //Converting the string to char* and then making it mutable
                string str(token); //Converting char* to String 
                ans = str.size();
                token=strtok(NULL, " ");
            return ans;

Log in to reply

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