My C++ Solution


  • 9
    class Solution {
    public:
        int lengthOfLastWord(const char *s) {
            int len = strlen(s);
    		if (!len) return 0;
    		int n=0,  i = len-1;
    		while (s[i] == ' ') i--;
    		for (; i >= 0; i--,n++)
    			if (s[i] == ' ')
    				return n;
    		return n;
        }
    };

  • 0
    C

    std::string will provide you with .length() .size() in constant time (C++11) where as in this case the plain strlen(s) is O(n). Basically you scan the string twice in the above solution.

    1. First with strlen() from begin to end '0'
    2. Second from end to first space character.

    IMHO, key to tackling this problem (with speed) is to scan the string only once.


  • 0
    X

    l use istringstream instead

    class Solution {
    public:
        int lengthOfLastWord(string s) {
            string word("");
    	istringstream ss(s);
    	while (ss >> word){}
    	return word.size();
        }
    };
    

  • 0
    A

    @chammika Haha, true. But he chose C, so he gets a bare char pointer. That makes it harder to solve this problem in one forward scan.


Log in to reply
 

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