58. Length of Last Word(最后一个单词的长度)

题目链接:https://leetcode.com/problems/length-of-last-word/

易错点在于要处理字符串后面的空格。

用s=s.trim();来保证。

AC 2ms 100% Java:

class Solution {
    public int lengthOfLastWord(String s) {
        int ans=0;
        s=s.trim();
        for(int i=s.length()-1;i>=0;i--){
            if(s.charAt(i)==' ')
                break;
            else
                ans++;
        }
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/God_Mood/article/details/88091735