Why is this code not working for this Question?

Why is this code not working for this Question?


hello @cbcao263
remove 2nd if statement of for loop and then try

Sir, I have done this and it was not passing for text case like " ", So I used one more loop for that having in which I calculated Spaces and then used An another condition for(int i=0;i<n;i++)
{
if(s[i]==32)
sp++;
}
if(sp==n)
return 0;

Then It was failing for the condition "a ".

And As You told to remove the second line, What was issue in that Sir?

compiler was treating len++ as an inside statement of if , thats why i said to remove it.

if ur code is still failing then pls share ur updated code with me


This is the code


Even This is not working as I used the {} for the if.

class Solution {
public:
int lengthOfLastWord(string s) {
    if(s.length()==0)
        return 0;
    int len=0,sp=0;
    int n=s.length();
    int i=n-1;
    // code for skipping all end spaces 
    while(i>=0 && s[i]==' ')
        i--;
    
    
    for(;i>=0;i--)
    {
        if(s[i]==32 and len!=0)
            break;
        
        
        len++;
    }
    return len;
}
};

check now .
basically u need to skip ending spaces and for that i have added while loop.

Accepted Sir,
Basically You have skipped the spaces at last and then you start calculating the word length.
Am I right?

yeah…correct…

Thanks a lot Sir for this Method, found One New Method today :slight_smile:

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.