Single Loop, two pointer , O(n) complexity approach


#1

#Approach
#word lie between two spaces "n spaces "+word+“n spaces”
#pointer i and j traverse towards left until it finds a char
#if it finds the char ,i would stop and j still traverses towards left till it finds a space.
class Solution:
# @param A : string
# @return an integer
def lengthOfLastWord(self, A):
n=len(A)-1
i,j=n,n #point to the end
index=0

    while index<=n:
        if A[i]==" ":
            i=i-1
            j=j-1
            
        if A[j]!=" ":
            j=j-1
        
        if A[j]==" " and A[i]!=" " :
            break
        index=index+1
        
    if index==n:
        return i
    else:
        return i-j