給定字符串 s,返回最後一個單詞的長度。單詞由非空格字符組成。若不存在返回 0。
find_last_not_of(' ') 找到最後非空格字符位置 end。若不存在返回 0。
find_last_of(' ', end) 找到 end 之前最後一個空格位置 start(若無則為 npos,視為 -1)。
長度 = end - start。
class Solution {
public:
int lengthOfLastWord(string s) {
int end = s.find_last_not_of(' ');
if (end == string::npos) return 0;
int start = s.find_last_of(' ', end);
return end - start;
}
};