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))
    

      

    既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
  • 相关阅读:
    阿里云中挖矿病毒
    flutter 返回刷新页面
    PM2 常用命令
    阿里云Redis 配置
    stm32f407启动文件分析
    C++类的前置声明
    Qt快速入门学习笔记(画图篇)
    Qt快速入门学习笔记(基础篇)
    Qt入门实例
    Qt编码设置
  • 原文地址:https://www.cnblogs.com/xiaodongsuibi/p/8655287.html
Copyright © 2011-2022 走看看