Length of last word

 58. Length of Last Word

Easy

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

word is a maximal 

 consisting of non-space characters only.

 

Example 1:

Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.

Example 2:

Input: s = "   fly me   to   the moon  "
Output: 4
Explanation: The last word is "moon" with length 4.

Example 3:

Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.

 

Constraints:

  • 1 <= s.length <= 104
  • s consists of only English letters and spaces ' '.
  • There will be at least one word in s.

myCode.py:
  • 1
class Solution: def lengthOfLastWord(self, s: str) -> int: return len(s.split()[-1])

  • 2
class Solution: def lengthOfLastWord(self, s: str) -> int: c='' a=[] for i in range(len(s)): if s[i]==' ': if c!='': a.append(c) c='' continue c+=s[i] if c!='': a.append(c) print(a) return(len(a[-1]))

otherCode.py:

Explanation

  • iterate throughout the list from right to left
  • ignore all whitespaces
  • when reaching the alphabet character count all adjacent non-whitespace elements and return the result when reaching a whitespace element

Code:

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        result = 0
        for i in range(len(s)-1, -1, -1):
            if s[i] != " ":
                result += 1
            elif result:
                return result

        return result

Algorithm complexity:
Time complexity: O(n).
Space complexity: O(1).

Other.cpp:

Code

class Solution {
public:
    int lengthOfLastWord(string s) {
      stack<char> s1;
      int count=0;
      for(int i=0;i<s.size();i++){
          s1.push(s[i]);
      }
//here we push all the element of the string to stack

/*
now we will pop() all the blank spaces from the top of stack so 
that we reach the last later of the last word.
*/

    while(s1.top()==' ')s1.pop();

/*
now we run the while loop util the stack is empty in the case of 
only one word is there or the blank space comes which seperate the two words.

*/

      while(!s1.empty()&&s1.top()!=' '){
        count++;
        s1.pop();
          
    }
// now we itterate the count to count the length of the last word and return  it.

    return count;

    }
};

Comments

Popular posts from this blog