Question: Given a string s consisting of words and spaces, return the length of the last word in the string. (C++) class Solution { public: int

Given a string s consisting of words and spaces, return the length of the last word in the string. (C++)

class Solution {

public:

int lengthOfLastWord(string s) {

int n = s.length();

int ptr = n-1;

while(s[ptr] >=0 && s[ptr] == ' ')

ptr--;

int len = 0;

while(ptr >= 0 && s[ptr--] != ' ') // This line

len++;

return len;

}

};

For this solution, why does s[ptr--] have the -- in the second while loop?

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!