Leetcode 58 Length of Last Word 句子中最後一個詞的長度
阿新 • • 發佈:2019-02-09
題目描述:
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
思路:
1.從後往前,先跳過末尾的空格,再數字母的個數
2.時間複雜度O(n),n是句子長度,最差情況下句子末尾全都是空格,比如“apple ”,此時就需要遍歷整個句子。
程式碼:
class Solution {
public:
int lengthOfLastWord(string s)
{
int n=s.size(),ans=0,i=n-1;
while(s[i]==' ')
i--;
while(i>=0 && s[i] != ' ')
{
ans++;i--;
}
return ans;
}
};