JAVA算法:最后一个单词的长度(JAVA代码)
给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。
如果不存在最后一个单词,请返回 0 。
说明:一个单词是指由字母组成,但不包含任何空格的字符串。
算法设计
package com.bean.algorithm.basic;public class LengthofLastWord {public int lengthOfLastWord(String s) {if (s.length() == 0 || s == null)return 0;int slong = 0;int lastLong = 0; // 记录最后一个word的长度for (int i = 0; i < s.length(); i++) {if (s.charAt(i) == ' ') {slong = 0;} else {slong++;lastLong = slong;}}return lastLong;}public static void main(String[] args) {// TODO Auto-generated method stubString s="Given a string s consists of "+ "upper/lower-case alphabets "+ "and empty space characters";LengthofLastWord lfw=new LengthofLastWord();int result = lfw.lengthOfLastWord(s);System.out.println("result = "+result);}}
程序运行结果:
result = 10