[알고리즘] leetcode - 58번

Ss·2025년 3월 19일

문제

  • 문제
    주어진 문자열에서 마지막 단어의 길이를 구하는 문제입니다.
    단어는 공백으로 구분되며, 마지막 단어 뒤에는 공백이 없고, 앞에만 있을 수 있습니다.

  • 조건

  1. 1 <= s.length <= 10^4
  2. s는 영어 알파벳과 공백으로만 구성됩니다.
  • 예시
    예제 1
    입력: "Hello World"
    출력: 5
    설명: "World"는 길이가 5입니다.

예제 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;
  }
}

0개의 댓글