1. 程式人生 > >(C++練習) 58. Length of Last Word

(C++練習) 58. Length of Last Word

NPU upper pty style The world per 字串 lower

題目 :

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.

Example:Input:

  "Hello World"

  Output: 5

大意 :

找出最後一個字串的長度, 利用space characters 來判斷

解法 : 直接從最後面開始計數字串的長度, 遇到space即回傳長度

 1 class Solution {
 2 public:
 3     int lengthOfLastWord(string s) {
 4         
 5         int len = strlen(s.c_str()) - 1;
 6 
 7         int ans = 0;
 8         for (int i = len; i >= 0; i--){
 9             if (s[i] != 
) ans++; 10 else if (ans) return ans; 11 } 12 13 return ans; 14 } 15 };

 

(C++練習) 58. Length of Last Word