原题
Given a string s consists of upper/lower-case alphabets and empty space characters ’ ‘, return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
大意
给定一个字符串s,由大写字母、小写字母和空格组成,返回字符串中最后一个字段的长度,如果不存在最后一个字,则返回0
思路
除去字符串两头的空格,然后使用倒序的方法遍历字符串,如果出现空格,则统计空格之前字符的个数。
代码
public class Solution {
public int lengthOfLastWord(String s) {
//去除字符串两边的空的字符串
String str=s.trim();
int j=0;
int n=str.length();
//倒序取出遍历字符串中的字符,计算直至出现空格的字符的个数
for(int i=n-1;i>=0;i--){
if(str.charAt(i)-'A'>=0)
j++;
else return j;
}
return j;
}
}