Leetcode -58 Length of Last Word

 In this problem there given a string we need to find length of last word this problem solve using stack and my approach is without using stack both are acceptable first my approach explain these are input 

Input: "hello Accenture iam vinaykumar"

Output: 10

Explaination: the last word is "vinaykumar" so the length is 10

Input: "Hello world"

Output: 5

Explaination: the last word is "world" so the length is 5

Input: " fly me to the moon "

Output: 4

Explaination: the last word is "moon" so the length is 4

The my approach logic is:

Here we need traversal in reverse direction and count the counter until the first space come then space come break the loop and return the count but it's not work because there is space at staring of reverse order travesel it's difficult so we need count space also  int m=0; this is space count and  int count=0; this is actual last word length count first for loop for space count when there is space s[i]==' ' at starting in reverse travesal it count until the the s[i]!=' ' and second for loop for word count i=n-1-m this is condition for where to start count s[i]!=' ' the word until the next space come s[i]==' ' else condition break the entire loop and return the count

Without using stack this is the code of C++:

class Solution {
public:
    int lengthOfLastWord(string s) {
        int n=s.size();
        int i,j;
        int count=0,m=0;
        for(i=n-1;i>=0;i--){
            if(s[i]==' '){
            m++;
            }
            else{
                break;
            }
        }
        for(i=n-1-m;i>=0;i--){
            if(s[i]!=' '){
                count++;
            }
            else{
                break;
            }
        }
        return count;
    }
};

With using stack this is code of C++:

class Solution {
public:
    int lengthOfLastWord(string s) {
        int count=0;
        stack <char> k;
        for(int i=s.length()-1;i>=0;i--)
        {
            if(s[i]!=' ')
            {
                k.push(s[i]);
            }
            else if(s[i]==' ')
            {
                if(!k.empty())
                  break;
                else
                  continue;
            }
        }
        while(!k.empty())
        {
            k.pop();
            count++;
        }
        return count;
    }
};

my leetcode profile given below:

https://leetcode.com/u/vinaykumar333j/

my greekforgreek profile given below:

https://www.geeksforgeeks.org/user/vinaykum6ho4/

Post a Comment

0 Comments