leetcode -58. Length of Last Word


問題描述:
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.

題目分析

題目要求求一字符串最后一個單詞的長度(字符串由大小字母和空格組成),如果不存在最后一個單詞,則返回0。

注意:單詞是指僅有非空字符組成字符序列

s="Hello world   "
return 5.

字符串s中world 后有若干空格,但空格并不屬于單詞,因此s中最后一個單詞是指world。

解題思路

題目中要求最后一個單詞的長度,即字符串s從后邊開始,從第一非空字符開始查找空格,空格所在位置與第一個非空字符位置索引差即為最后一個單詞的長度。如上例中字符串s,字符d所在位置索引與Hellow 和world之間的空格所在位置索引之差即為單詞world的長度。

代碼


#include <stdio.h>
#include <string.h>

int lengthOfLastWord(char* s) {
    
    int l=strlen(s);           //字符串長度
    printf("l=%d",l);          
    int i,j=0;
    
    if (l==0)                  //空字符串
        return 0;
        
    for(i=l;i>0;i--)           //第一個非空字符所在位置
    {
        if(*(s+i-1)!=32)       //當字符串由空格組成時,查找到最后一個字符時i=1,i--后等于零結束循環
           break;
    }
    printf("i=%d",i);
    
    if(i==0)                  //若找不到第一個非空字符,即字符串由若干空格組成
        return 0;
        
    for(j=i-1;j>0;j--)        //查找非空字符前邊的第一個空格,當字符串中只有一個單詞時,即j=1時仍未找到空格,
                              //j--等于零,結束循環
    {
        if(*(s+j-1)==32)
            break;
    }

   return i-j;

}

int main ()
{
    char *strs="a  a    ";
    
    int llw,i=0;
    int size=strlen(strs);
    printf("size=%d\n",size);
    llw=lengthOfLastWord(strs);
    printf("size=%d\n",size);

    printf("%c\n",*(strs+size-1));
    
    printf("llw=%d\n",llw);
    
    return 0;
}

參考文獻
[1] http://shmilyaw-hotmail-com.iteye.com/blog/2293842

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容