Leetcode#58. Length of Last Word

来源:互联网 发布:淘宝宝贝宣言词怎么写 编辑:程序博客网 时间:2024/05/20 14:17

题目

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.

题意

给一个字符串分隔符为空格,求出字符串中最后一个单词的长度输出。

思路

从后向前找。

C++语言

class Solution {public:    int lengthOfLastWord(string s)     {        int start = s.size()-1,res = 0;        for(int i = s.size()-1; i>=0; i--)        {            if(s[i] != ' ')            {                start = i;                  break;            }        }        for(int i = start; i>=0; i--)        {            if(s[i]!=' ')                res++;            else                break;        }        return res;    }};

Python语言

注意range(n,m,d)代表从n 到m-1,每次增加d个。

class Solution(object):    def lengthOfLastWord(self, s):        """        :type s: str        :rtype: int        """        res = 0        start =len(s)-1        for index in range(len(s)-1,-1,-1):            if s[index]!=" ":                start = index                break        for index in range(start,-1,-1):            if s[index]!=" ":                res = res + 1            else:                break        return res
原创粉丝点击