皮卡丘python写leetcode——Day4

·题目描述:

给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。

单词 是指仅由字母组成、不包含任何空格字符的最大
子字符串
。

 

示例 1:

输入:s = "Hello World"
输出:5
解释:最后一个单词是“World”,长度为5。
示例 2:

输入:s = "   fly me   to   the moon  "
输出:4
解释:最后一个单词是“moon”,长度为4。
示例 3:

输入:s = "luffy is still joyboy"
输出:6
解释:最后一个单词是长度为6的“joyboy”。

·使用函数re.findall()

re.findall() 是 Python 中正则表达式库 re 的一个函数,用于在字符串中查找所有非重叠匹配项,并返回一个包含这些匹配项的列表。

re.findall(pattern, string, flags=0)

import re  
  
# 查找所有数字  
text = "我有1个苹果和2个橙子,总共3个水果。"  
numbers = re.findall(r'\d+', text)  
print(numbers)  # 输出: ['1', '2', '3']  
  
# 查找所有英文单词  
text = "Hello, world! This is a test."  
words = re.findall(r'\b\w+\b', text)  
print(words)  # 输出: ['Hello', 'world', 'This', 'is', 'a', 'test']  
  
# 查找所有邮箱地址  
text = "Contact us at info@example.com or support@example.org"  
emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', text)  
print(emails)  # 输出: ['info@example.com', 'support@example.org']

·解题代码:

class Solution(object):
    def lengthOfLastWord(self, s):
        words = re.findall(r'\b\w+\b',s)
        size = len(words)
        return len(words[size-1])

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值