LC 58. Length of Last Word

Nilanjan Deb · April 5, 2020

This is my CPP solution.

class Solution {
public:
    int lengthOfLastWord(string s) {
        while(s.size()>0 && s[s.size()-1]==' '){
            s.pop_back();
        }
        int n = s.size();
        if(n == 0){
            return 0;
        }
        int cnt = 0;
        for(int i=0;i<n;i++){
            if(s[i] == ' '){
                cnt ++;
            }
        }
        if(cnt==0){
            return n;
        }
        cnt = 0;
        for(int i=n-1;i>=0;i--){
            cnt++;
            if(s[i]==' '){
                cnt--;
                break;
            }
        }
        return cnt;
    }
};


Dicussion Forum