My c 0ms solution o(n)time


  • -1
    R
    // "",     0
    //" ",	0
    //" a",	1
    //"a   "	1
    //"       ",0
    
    int lengthOfLastWord(char* s) {
    	if (s[0] == '\0')
    		return 0;
    	int sLen = 0;
    	while (s[sLen++] != '\0')
    		;
    	sLen = sLen - 1;
    	int lastWordLen = 0;
    	while (sLen >= 1 && s[sLen - 1] == ' ')
    		sLen--;
    	for (int i = sLen - 1; i >= 0; i--)
    	{
    		if (s[i] != ' ')
    		{
    			lastWordLen++;
    		}
    		else
    			break;
    	}
    	return lastWordLen;
    }

Log in to reply
 

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