題目描述
鏈接:https://leetcode-cn.com/problems/length-of-last-word/
給你一個(gè)字符串 s,由若干單詞組成,單詞前后用一些空格字符隔開。返回字符串中最后一個(gè)單詞的長(zhǎng)度。
單詞 是指僅由字母組成、不包含任何空格字符的最大子字符串
示例
輸入:s = "Hello World"
輸出:5
代碼
// 題解:https://leetcode-cn.com/problems/length-of-last-word/solution/zui-hou-yi-ge-dan-ci-de-chang-du-by-leet-51ih/
public int lengthOfLastWord(String s) {
if (s == null) {
return 0;
}
// 反向遍歷
int i = s.length() - 1;
while (i >= 0 && s.charAt(i) == ' ') {
i --;
}
int res = 0;
while (i >= 0 && s.charAt(i) != ' ') {
res ++;
i --;
}
return res;
}