백준&LeetCode
[LeetCode] 58. Length of Last Word (Day3)
py0922
2024. 1. 10. 12:41
Given a string s consisting of words and spaces, return the length of the last word in the string.
A word is a maximal
consisting of non-space characters only.
첫 번째
일단 풀었는데, runtime이 2ms라서 다시 풀어야한다. runtime 0ms되기까지!
class Solution {
public int lengthOfLastWord(String s) {
String[] words = s.trim().split("\\s+");
int count = words.length;
String res = words[count-1];
return res.length();
}
}

두 번째
결국 다른 분꺼 참고해서 풀었다. 마지막 단어 인덱스만 구하면 되었으므로 마지막 단어 맨 뒤 인덱스랑 맨 앞 인덱스를 찾아서 뒤 인덱스 - 앞 인덱스를 빼주면된다.
class Solution {
public int lengthOfLastWord(String s) {
int i = s.length() - 1;
while(i>=0 && s.charAt(i) == ' ') --i;
final int lastIndex = i; // 마지막 단어 맨 뒤
while(i>=0 && s.charAt(i) != ' ') --i; // 마지막 단어 맨 앞
return lastIndex - i;
}
}

반응형
LIST