leetcode with python:434. Number of Segments in a String

题目:

Given a string s, return the number of segments in the string.

A segment is defined to be a contiguous sequence of non-space characters.

给定一个字串,判断里面有几个segment
segment指无空白的连续字元(像是单字)
ex:input:"Hello, my name is John"=>output:5
explanation: The five segments are ["Hello,", "my", "name", "is", "John"]

先写个比较正规的写法

class Solution:    def countSegments(self, s: str) -> int:        ans=0        i=0        while i<len(s):            if s[i]!=" ":                ans=ans+1                while i<len(s) and s[i]!=" ":                    i=i+1            else:                i=i+1                        return ans

遍历该字串
遇到非空白字元ans就+1,接着让i脱离该segment再继续往下走
直到完全遍历,回传ans
最后执行时间34ms(faster than 85.49%)

当然应该也不少人发现这题在python其实异常轻鬆

class Solution:    def countSegments(self, s: str) -> int:        s=s.split()        return len(s)

将字串split,回传split出来的阵列长度即可
最后执行时间24ms(faster than 98.76%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章