LASTWORD-Editorial

PROBLEM LINK:

PRACTICE
Editorialist: Aditya Verma

DIFFICULTY:

EASY

PREREQUISITES:

String

PROBLEM:

Chef had got lots of homework and he have to do it fast. So, he wants your help Can u help him?
The problem is to find the length of the last word.

Input:

A string consists of upper/lower-case alphabets and empty space characters ’ '.

Output:

An integer value of the length of the last word.

Example 1:

Input:

My Business is my Business None of your Business

Output:

8

Explanation:

The last word is Business. Its length is 8.

Example 2:

Input:

Bharat

Output:

6

EXPLANATION:

So According to the question, we have to find the length of the last word so we will traverse the string from the last until we encounter space character.

SOLUTION:

#include <bits/stdc++.h>
using namespace std;
int last(const string A) {
    int count=0,ch=0;
    int len = A.length();
        for(int i=len-1;i>=0;i--){
            if(A[i]!=' '){
                count++;
                ch++;
            }
            else if(ch>0 and A[i]==' ')
                break;
        }
        return count;
}
int main(void){
    string str;
    getline(cin, str);
    int ans = last(str);
    cout<<ans<<endl;
}