题目:
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
C#版本的代码如下(关键步骤已经注释):
public static int LengthOfLastWord(string s)
{
//将字符串分隔开
string[] midtest = s.Split(' ');
int result=;
//从最末尾一个开始向前搜索第一个非空值
for (int i = midtest.Length - ; i >= ; i--)
{
string test = midtest[i];
//找到第一个不为空的情况
if (!string.IsNullOrEmpty(test))
{
result = test.Length;
break;
}
}
return result;
}
再次运行时间为最少的,小嘚瑟,哈哈