自学内容网 自学内容网

Leetcode 434. Number of Segments in a String

Problem

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.

Algorithm

Counts the number of words (non-empty segments) in a string by traversing it and skipping spaces.

Code

class Solution:
    def countSegments(self, s: str) -> int:
        cnts, index = 0, 0
        sLen = len(s)
        while index < sLen:    
            while index < sLen and s[index] == ' ':
                index += 1
            if index < sLen and s[index] != ' ':
                cnts += 1
            while index < sLen and s[index] != ' ':
                index += 1
        return cnts

原文地址:https://blog.csdn.net/mobius_strip/article/details/142892039

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!