[leetcode]58. Length of Last Word

从后往前,先找到一个非空格的,开始计数,一直向前找,如果找到一个空格停下。
利用两个空格之间,是一个单词的原理

class Solution {
    public int lengthOfLastWord(String s) {
        int tail=s.length()-1;
        int len=0;
        while(tail>=0&&s.charAt(tail)==' ')tail--;
        while(tail>=0&&s.charAt(tail)!=' '){
            len++;
            tail--;
        }
        
        return len;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_36869329/article/details/85201466