给定一个字符串,包含大小写英文字母,计算最右一个字的长度。
空字符等返回0.
C++版本。
class Solution {
public:
int lengthOfLastWord(const char *s) {
if(NULL == s || s == '\0') return 0; //spacial case
const char *bch = s;
while(*bch == ' ' && *bch != '\0') bch++;
if(*bch == '\0') return 0;
//find the last char
const char *pch = bch;
while(*pch != '\0') pch++;
pch--; //back to last char
//need to skip whitespaces
while(*pch == ' ')pch--;
int rvl = 0;
while(*pch != ' ' && pch != bch) {
pch--;
rvl++;
}
if(pch == bch) rvl++;
return rvl;
}
};
Java版本.
public class Solution {
public int lengthOfLastWord(String s) {
if(null == s || s.trim().length() == 0) return 0;
String[] words = s.split("\\s+");
return words[words.length -1].length();
}
}