Skip to content

Latest commit

 

History

History
79 lines (63 loc) · 1.51 KB

58. Length of Last Word.md

File metadata and controls

79 lines (63 loc) · 1.51 KB

Solution:

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        l=s.split()
        w=l[-1]
        return len(w)

Approaches

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        
        n=len(s)
        #l=[]
        for i in range(n):
            if s[i]==" ":
                #l.append(i)
                l=i
            else:
                continue
        
        #l.sort()
        #return l[-1]
        lw=s[l+1:n] #last word
        ans=len(lw)

        return ans
class Solution:
  def lengthOfLastWord(self, s: str) -> int:
      
      n=len(s)
      l=[]
      for i in range(n):
          if s[i]==" ":
              l.append(i)    
      m=len(l)

      slices=[]

      for j in range(m-1):
          a=l[j]
          b=l[j+1]

          k=s[a+1:b]
          slices.append(k)
      
      if slices!=[]:
          return len(slices[-1])
      else:
          return 0
class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        n=len(s)
        k=(n//2)+1
        for i in range(k):
            s[i], s[-1-i]=s[-1-i], s[i]

        w=[]
        i=0
        while s[i]!=" ":
            w.append(s[i])
            i=i+1
        
        return len(w)

error: it's a string! immutable! logic error: while it is not equal is wrong, first element being " " will make it false and pointless it'll get too complicated for an easy problem if we make it an array to proceed