JAVA/Coding Test Study
[Easy] LeetCode - no.58 Length of Last Word : Java
♡˖GYURI˖♡
2024. 10. 13. 04:33
728x90
문제
주어진 String s의 마지막 단어의 길이를 return할 것
Example 2:
Input: s = " fly me to the moon " Output: 4 Explanation: The last word is "moon" with length 4.
풀이
class Solution {
public int lengthOfLastWord(String s) {
s = s.trim();
String[] str = s.split(" ");
return str[str.length - 1].length();
}
}
- trim()과 split() 사용
- trim()으로 앞 뒤 공백 제거 후, split(" ")을 사용하여 String 배열로 변환
- 맨 마지막 인덱스의 String 값의 길이를 반환
- 시간복잡도 : O(N)