Programming/LeetCode

[LeetCode] #58. Length of Last Word (repeat : 0)

dev.pudding 2024. 1. 23. 09:15
728x90

Description

Given a string s consisting of words and spaces, return the length of the last word in the string.
A word is a maximal substring 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.


Solution 

class Solution {
    public int lengthOfLastWord(String s) {
        String[] sep = s.split(" ");
        String result = "";
        for(int i=0; i<sep.length; i++){
           result = sep[i];
        }
        return result.length();
    }
}

Approach 

1) split the string with spaces using split() method 

2) iterate till the end of the array

3) store the last element to the result 

4) return the length of the string which will be the number of elements in the string

Performance

In terms of time complexity , it is o(n) , and the n represents the number of elements in the array 

In terms of space complexity , it is O(1) . the variables are independent from the input size of the array.

 

 

https://leetcode.com/problems/length-of-last-word/description/?envType=study-plan-v2&envId=top-interview-150

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com