自己写的是调API
public int lengthOfLastWord(String s) {
s = s.trim();
return s.length() - 1 - s.lastIndexOf(" ");
}
从后向前遍历
代码思路来源:
https://leetcode-cn.com/problems/length-of-last-word/solution/hua-jie-suan-fa-58-zui-hou-yi-ge-dan-ci-de-chang-d/
public int lengthOfLastWord(String s) {
int end = s.length() - 1;
while (end >= 0 && s.charAt(end) == ' ') end--;
int start = end;
while (start >= 0 && s.charAt(start) != ' ') start--;
return end - start;
}