/** * 【题目名称】最后一个单词的长度<p> * 【题目来源】https://leetcode.cn/problems/length-of-last-word/description/ * * @author 潘磊,just_panlei@just.edu.cn * @version 1.0 */classSolution{/** * 返回给定字符串最后一个单词的长度。 * * @param s 给定字符串。 * @return s中最后一个单词的长度。 */publicintlengthOfLastWord(Strings){char[]chars=s.toCharArray();// 将s转存为字符数组处理intend=s.length()-1;// 最后一个英文字母的位置,初始为字符串最后一个字符的位置intstart;// 最后一个单词的首字母位置之前的一个位置/* 定位最后一个英文字母的位置 */while(chars[end]==' '){end--;}start=end;/* 定位最后一个单词的起始位置 */while(start>=0&&chars[start]!=' '){start--;}returnend-start;// 计算并返回最后一个单词的长度}}/** * 【题目名称】最后一个单词的长度<p> * 【题目来源】https://leetcode.cn/problems/length-of-last-word/description/ * * @author 潘磊,just_panlei@just.edu.cn * @version 2.0 */classSolution{/** * 返回给定字符串最后一个单词的长度。 * * @param s 给定字符串。 * @return s中最后一个单词的长度。 */publicintlengthOfLastWord(Strings){String[]words=s.split(" +");// 通过空格将s分割为若干单词intn=words.length;// s中有效单词的个数returnwords[n-1].length();// 返回最后一个单词的长度}}