본문 바로가기
Problem Solving/LeetCode

[LeetCode] 58. Length of Last Word - Java

by graycode 2026. 5. 19.

 문제 링크

 

Length of Last Word - LeetCode

Can you solve this real interview question? Length of Last Word - 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:

leetcode.com

 

 풀이 코드

public class Solution {

    public int lengthOfLastWord(String s) {
        int i = s.length() - 1;
        while (i >= 0 && s.charAt(i) == ' ') i--;
        int j = i;
        while (j >= 0 && s.charAt(j) != ' ') j--;

        return i - j;
    }

}

댓글