【LeetCode】C# 58、Length of Last Word

来源:互联网 发布:软件项目研究成果报告 编辑:程序博客网 时间:2024/06/05 20:12

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.

求最后一个单词的长度。

思路:,利用string.Trim()去掉字符串最左和最右的空格,后从后往前遍历,从第一个字符开始到第一个空格结束。

public class Solution {    public int LengthOfLastWord(string s) {        s = s.Trim();        int lastIndex = s.LastIndexOf(' ') + 1;        return s.Length - lastIndex;            }}
原创粉丝点击