문제
주어진 문자열에서 마지막 단어의 길이를 구하는 문제입니다.
단어는 공백으로 구분되며, 마지막 단어 뒤에는 공백이 없고, 앞에만 있을 수 있습니다.
조건
예제 2
입력: " fly me to the moon "
출력: 4
설명: "moon"의 길이는 4입니다.
해결
문제를 제대로 읽지 않아 쓸대없는 제출을 하게됐다.
.
class Solution {
int lengthOfLastWord(String s) {
// Initialize the index variable to the last index of the string
int index = s.length - 1;
// Loop through any trailing spaces at the end of the string
while (s[index] == " "){
index--;
}
// Initialize the count variable to 0
int count = 0;
// Loop through the last word in the string
while(s[index] != " "){
// Increment the count variable for each character in the last word
count++;
// Check if the previous character was a space or if we have reached the beginning of the string
if (s[index] == " " || index == 0){
// Break out of the loop if the previous character was a space or if we have reached the beginning of the string
break;
}
// Move the index to the previous character in the string
index--;
}
// Return the count variable which contains the length of the last word in the string
return count;
}
}
class Solution {
int lengthOfLastWord(String s) {
s = s.trim();
final words = s.split(" ");
return words[words.length-1].trim().length;
}
}