[leetcode] Array/String (Easy) - 58. Length of Last Word

brandon·2025년 7월 9일
0

leetcode-array/strings

목록 보기
18/20

Intuition

뒤에서부터 세기.

답안

class Solution {
    public int lengthOfLastWord(String s) {
        int length = s.length();
        boolean letterCameUpAlready = false;
        int count = 0; 

        for (int i = length - 1; i >= 0; i--) {
            if (letterCameUpAlready && s.charAt(i) == ' ') {
                return count;
            }

            if (!letterCameUpAlready && s.charAt(i) != ' ') {
                letterCameUpAlready = true;
                count++;
            } else {
                if (letterCameUpAlready) {
                    count++;
                }
            }
        }

        return count;
    }
}
profile
everything happens for a reason

0개의 댓글