Solution by raunaksabhani


  • 1
    R

    Approach #1 Start from the beginning of the string [Accepted] [6ms]

    Intuition

    Split the string at an empty space i.e ' ' character. Get the word starting
    after the last empty space character in the string

    Algorithm

    Use the string split() function to split the string at the ' ' character.
    We then return the length of the last word which is stored in the last index of the array returned by the split() function

    Java

    public class Solution {
        public int lengthOfLastWord(String s) {
            String[] sArray = s.split(" ");
            if (sArray.length == 0)
                return 0;
            return sArray[sArray.length-1].length();
        }
    }
    

    Complexity Analysis

    • Time complexity : $$O(n)$$.

    The split() call on the string will iterate over the string once and split it into multiple strings. Time complexity of this operation is O(n).

    The length() call on the last word will iterate on the last word once. The worst case time complexity of this operation is O(n). This will happen when the string has only one word.

    • Space complexity : $$O(n)$$. The array returned by split() will contain all the words of the string. Thus the total space will be O(n)

    Approach #2 Starting from the end of the string [Accepted] [5ms]

    Algorithm

    We will convert the string to a character array. Start iterating from the end of the string
    We will iterate until we encounter the first empty character which has a non empty character to the right of it

    Java

    class Solution {
        public int lengthOfLastWord(String s) {
            char[] sArray = s.toCharArray();
            int end=sArray.length-1;
            if (end==-1)
                return 0;
            while (end >= 0 && sArray[end] == ' ') {
                end--;
            }
            for(int j=end;j>=0;j--)
            {
                if (sArray[j] == ' ')
                    return end - j;
            }
            return end+1;
        }
    }
    

    Complexity Analysis

    • Time complexity : $$O(n)$$. The toCharArray() function will take O(n) to convert the string into a character array. We then iterate from the end of the string to the first whitespace. In the worst case this cane be O(n) time i.e. when there is a single word

    • Space complexity : $$O(n)$$. The space taken to store the character array


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.