題目:
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;
}