·题目描述:
给你一个字符串 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])