1. 程式人生 > >leetcode 58. Length of Last Word(C語言,計算最後一個單詞的長度)19

leetcode 58. Length of Last Word(C語言,計算最後一個單詞的長度)19

貼原題:

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.

解析:
  本題是要計算一個字串中最後一個單詞的長度,每隔一個空格即算一個單詞。
  那麼簡單地想,我只要從字串的最後一個字元開始往前掃描,掃描到空格即跳出,否則計數器加一即可。
  但是我們必須考慮這個字串的最後幾位是空格怎麼辦的問題,以及這是個空字串等。我第一次提交的時候便沒有考慮到字串最後幾位是空格的情況導致出錯。引以為戒。下面程式碼中第二個if中與上n即解決了這個問題。

C程式碼:

int lengthOfLastWord(char* s) {
    int len=strlen(s);
    int n=0;//計數器,記錄最後一個單詞的長度
    for(int i=len-1
; i>=0; i--)//從後向前查詢 { if(*(s+i)!=' ')//不是空格則計數 { n++; } else if(*(s+i)==' ' && n)//檢測到空格即跳出 { break; } } return n; }