LeetCode OJ: 58. Length of Last Word
若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。 原文題目連結: https://leetcode.com/problems/length-of-last-word/ 。此題要在含有大小寫字母以及空白字元的字串裡,找出最後一個英文字的字母長度。如果不存在此英文字就輸出 0。 範例一 輸入:"Good morning " 輸出:7 範例二 輸入:"What a wonderful day" 輸出:3 演算法步驟如下: Step 1. 用一個變數 foundLen 紀錄目前找到的英文字長度,初值為0。 Step 2. 從字串最右邊開始找,一直找到不是空白字元為止。 Step 3. 當步驟 Step 2 找到不是空白字元時,foundLen = foundLen + 1。 Step 4. 當步驟 Step 3 找到是空白字元時,回傳 foundLen 。 程式碼如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 class Solution { public: int lengthOfLastWord(string s) { if (s.length() == 0 ) return 0 ; int foundLen = 0 ; for ( int i = s.length() - 1 ; i >= 0 ; i -- ) { if (s[i] == ' ' ) { if (foundLen > 0 ) return foundLen; continue ; } else { foundLen ++ ; } } return foundLen; } };