标签:style blog io ar color sp for on div
题目: 输入字符串 s,返回其最后一个单词的长度
如 s="Hello World" 返回5
s="Hello World " 返回5
s=" " 返回0
开始从前向后判断,超时了。改成从后向前判断,通过了。
class Solution { public: int lengthOfLastWord(const char *s) { int length = 0; int slen = strlen(s); for(int i = slen -1; i >= 0; i--) { if(s[i] == ‘ ‘) slen--; else break; } for(int i = slen - 1; i >=0; i--) { if(s[i] == ‘ ‘) break; else length++; } return length; } };
【leetcode】length of last word (easy)
标签:style blog io ar color sp for on div
原文地址:http://www.cnblogs.com/dplearning/p/4109449.html