【LeetCode】 117 最後一個單詞的長度

題目:

image-20210207015807576

image-20210207015656094

解題思路:

image-20210207015732013

https://leetcode-cn.com/problems/length-of-last-word/solution/hua-jie-suan-fa-58-zui-hou-yi-ge-dan-ci-de-chang-d/

代碼:

public class LC92 {
    public int lengthOfLastWord(String s) {
        int end = s.length() - 1;
        while(end >= 0 && s.charAt(end) == ' ') end--;
        if(end < 0) return 0;
        int start = end;
        while(start >= 0 && s.charAt(start) != ' ') start--;
        return end - start;
    }


    public static void main(String[] args) {
        LC92 lc = new LC92();
        System.out.println(lc.lengthOfLastWord("Hello World"));
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章