Try   HackMD

【LeetCode】 58. Length of Last Word

Description

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.

If the last word does not exist, return 0.

Note: A word is defined as a maximal substring consisting of non-space characters only.

給予一個字串包含大小寫英文字母和空白鍵,回傳字串中最後一個單字的長度。(最後一個單字指從左往右數最後一個出現的字)

如果最後一個單字不存在,回傳 0。

注意:一個單字定義為非空格組成的最長子字串。

Example:

Input: "Hello World"
Output: 5

Solution

  • C++中有個類別叫做stringstream非常好用,請務必學起來。
  • stringstream可以重新將字串串流化,也就是說你可以把字串當作stdin,然後用cin的方法來重新接收資料,常用於字串整理或是字串轉數字等。
  • 我們只需要用stringstream不停重新讀入原字串,直到最後一個字串取出他們長度即可。
    • 要注意只有空白、沒有字串的情況。

Code

class Solution { public: int lengthOfLastWord(string s) { stringstream ss(s); while(ss) { ss >> s; } string::iterator end_pos = remove(s.begin(), s.end(), ' '); s.erase(end_pos, s.end()); return s.length(); } };
tags: LeetCode C++