Question
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.
Thinking
如果使用C# Library提供的方法可以很快解出這題
public class Solution {
public int LengthOfLastWord(string s) {
var sArray = s.Trim().Split(' ');
var lastWord = sArray[sArray.Length - 1];
return lastWord.Length;
}
}
但以下我們想試試比較原始的方式
My C# Solution
public class Solution {
public int LengthOfLastWord(string s) {
var lastWordLength = 0;
for (var i = s.Length - 1; i >= 0; i--)
{
if (s[i].ToString() == " ")
{
if (lastWordLength == 0)
{
continue;
}
else
{
break;
}
}
lastWordLength++;
}
return lastWordLength;
}
}