zoukankan      html  css  js  c++  java
  • LeetCode Easy: 58. Length of Last Word

    一、题目

    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

    输出给定字符串的最后一个单词的长度

    二、解题思路

    我首先想到的就是从后往前遍历给定字符串,直到遇到空格位置,计数即可,AC之后,查看了网上的做法,比我简单多了,利用的是python中的切片功能split()方法。

    三、代码

    #coding:utf-8
    def lengthOfLastWord1(s):
        """
        :type s: str
        :rtype: int
        """
        if s == " ":
            return 0
        if len(s) == 1:
            return 1
        j = len(s)
        while s[j-1] != " ":
            j-=1
            # if j == 0:
            #     return
        count = len(s) - j
        print(count)
        return count
    
    def lengthOfLastWord2(s):
        tmp = s.split()
        if not len(tmp):
            return 0
        else:
            print(len(tmp[-1]))
            return len(tmp[-1])
    
    if __name__ == '__main__':
        s = "IndexError: string index out of range"
        lengthOfLastWord2(s)
        # print(s.split('i'))
        # print(s.split('i',1))
    

      

    既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
  • 相关阅读:
    ExtJs-学习篇(1)
    js中的Ajax经典示例
    软件工程开发流程
    Maven和Ajax
    搭建SSH框架
    拦截器
    OGNL
    Struts 2配置详解
    Struts 2入门
    HQL连接查询和注解
  • 原文地址:https://www.cnblogs.com/xiaodongsuibi/p/8655287.html
Copyright © 2011-2022 走看看