题目:
Given a string s consists of upper/lower-case alphabets and empty space characters ' '
, return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given s = "Hello World"
,
return 5
.
解题思路:
开始的思路(不严谨):
遍历整个s,若当前字符不为空格(' '),则count++;否则,令count=0,再重来。
开始的C程序(未通过):
<span style="font-size:12px;">int lengthOfLastWord(char* s) {
int count=0;
int len=strlen(s);
if(len==0) count=0;
else {
for(int i=0; i<len; i++){
if(s[i]!=' ') count++;
else count=1;
}
}
return count;
}</span>
错误原因:
测试的时候发现如下测试用例通不过(为了方便看,下例中用 ~ 表示空格):
"a~~b" "a~" "a~~" "~a" "~~~" 等
后来发现未考虑“有多个空格”、“以空格结尾”、“以空格开头”等问题。
更新思路:
1. 当遇到空格后,先继续遍历到空格结束,因为可能会有多个空格连着出现;
2. 注:当前字符不为空格时,令count=1,而不是count=0
C程序实现(通过):
int lengthOfLastWord(char* s) {
int count=0;
int len=strlen(s);
if(len==0) count=0;
else {
for(int i=0; i<len; i++){
if(s[i]!=' ') count++;
else {
while(s[i]==' ') i++;
if(s[i]=='\0') ;
else count=1;
}
}
}
return count;
}
别人的程序(引用):
我用的是数组实现,在讨论组里看到了别人的指针实现,很简洁巧妙,搬来看看:
int lengthOfLastWord(char* s) {
int lastLen = 0;
char* p = s + strlen(s) -1;
while(p>=s && isspace(*p)) p--;
while(p>=s && !isspace(*(p--))) lastLen++;
return lastLen;
}