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.
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
'Programming > LeetCode' 카테고리의 다른 글
[LeetCode] #232. Implement Queue using Stacks (0) | 2024.02.05 |
---|---|
[Leetcode] #14. Longest Common Prefix (repeat : 0 ) (0) | 2024.01.31 |
[LeetCode]#13. Roman to Integer (repeat : 0 ) (0) | 2024.01.22 |
[LeetCode] #169. Majority Element (repeat : 0 ) (0) | 2024.01.21 |
[LeetCode] #234 Palidrome LinkedList (repeat : 1) (0) | 2024.01.19 |