LeetCode:Length of Last Word(最後一個單詞的長度)
阿新 • • 發佈:2019-02-06
題目
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.全空格字串。
3.字串非全空格字串但結尾有空格。
針對這三種特殊情況,設計思路如下:
定義一個flag=1,標記是否找到非空格字元。從結尾找第一個非空格字元,用m記錄下標,置flag=0。找到非空格字元,開始尋找空格字元,找到後用n記錄下標並跳出。最後根據flag判斷,有非空格字元時,返回m-n即為單詞長度;沒有非空格字元就返回0。
程式碼
class Solution {
public:
int lengthOfLastWord(string s) {
int size = s.size();
if(!size)
return 0;
int n=-1;
int m=size;
int flag = 1;
for(int i=size-1;i>-1;i--)
{
if(s[i]!=' '&&flag)
{
m=i;
flag=0;
}
if(!flag)
{
if (s[i]==' ')
{
n=i;
break;
}
}
}
if(!flag)
{
return m-n;
}
else
return 0;
}
};