58. Length of Last Word

Intuition

find the last index of space


Approach

slice the string from the last index of space than return the length of the string


Complexity

Time complexity: O(n)

Space complexity: O(n)

Code

java

class Solution {

    public int lengthOfLastWord(String s) {

        s = s.trim();

        int lastIndex = s.lastIndexOf(" ");

        return s.substring(lastIndex+1).length();

    }

}

javaScript

/**

 * @param {string} s

 * @return {number}

 */

var lengthOfLastWord = function(s) {

    s = s.trim();

    let lastIndex = s.lastIndexOf(" ");

    s = s.slice(lastIndex+1);

    return s.length;

    

};

Comments

Popular posts from this blog

3Sum Closest: O(n²) Two-Pointer Magic šŸš€ leetcode: 16

Kadane's Algorithm: Maximum Subarray Problem - LeetCode(53) Solution

14. Longest Common Prefix