leetcode Length of Last Word

Length of Last Word

 Total Accepted: 64034 Total Submissions: 235032My Submissions

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.

For example, 
Given s = "Hello World",
return 5.


// test58lengthOfLastWord.cpp : 定義控制檯應用程序的入口點。
//


#include "stdafx.h"
#include "iostream"
#include "string"


using std::string;
int lengthOfLastWord(string s);


int _tmain(int argc, _TCHAR* argv[])
{
int n = lengthOfLastWord("  hello haha  ");
return 0;
}


/*
總共幾種情況
"hello"  "  hello world" "hello wor" "hello haha   " "   "
*/
int lengthOfLastWord(string s) 
{
int n = s.size();
if (n < 1)
return n;
int currentLen = 0;
int count = 0;
for (auto i = 0; i < n; i++)
{
if (s[i] == ' ')
{
if (count == 0)
continue;
else
{
currentLen = count;
count = 0;
continue;
}
}
count++;
}
if (count != 0)
currentLen = count;
return currentLen;
}

發佈了49 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章