58. 最后一个单词的长度

58. 最后一个单词的长度

https://leetcode-cn.com/problems/length-of-last-word/description/

package com.test;

/**
 * @Author stono
 * @Date 2018/8/22 下午4:09
 */
public class Lesson058 {
    public static void main(String[] args) {
        String s = "hello world ";
        s = "a ";
        s = "  ";
        int i = lengthOfLastWord(s);
        System.out.println(i);
    }

    public static int lengthOfLastWord(String s) {
        if ("".equals(s)) {
            return 0;
        }
        int res = 0;
        // 分割为数组
        char[] chars = s.toCharArray();
        int length = s.length()-1;
        // 去除末尾的空格
        for ( ; length> -1; length--) {
            char aChar = chars[length];
            if (aChar != ' ') {
                break;
            }
        }
        for (int i = 0; i <= length; i++) {
            char aChar = chars[i];
            // 遇到空格就清零
            if (aChar == ' ') {
                res = 0;
            } else {
                // 否则就不断累加
                res++;
            }
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/stono/p/9518442.html