↓Skip to main content
  1. LeetCode/

LeetCode 434: Number of Segments in a String

·1 min· ·
LeetCode Easy String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-24

  • Submissions: Accepted (first try)

Approach
#

A segment is a run of non-space characters. split() with no argument treats runs of spaces as one separator and drops leading and trailing spaces, giving an empty list for an empty string, so len(s.split()) is the answer (String Template 6).

My Solution
#

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

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • split(" ") leaves empty strings and overcounts.

Interview Explanation
#

I use split with no argument, which ignores extra spaces, and count the pieces; for O(1) space, count positions that are non-space and either first or preceded by a space.

Related

LeetCode 345: Reverse Vowels of a String
·1 min
LeetCode Easy Two-Pointers String
LeetCode 345 note: the same two pointers as LC 917, with the condition switched to “is a vowel” (both cases)
LeetCode 1446: Consecutive Characters
·1 min
LeetCode Easy String
LeetCode 1446 note: track the current run of equal characters in one pass, resetting to 1 on a change
LeetCode 1869: Longer Contiguous Segments of Ones than Zeros
·1 min
LeetCode Easy String
LeetCode 1869 note: find the longest run of 1s and of 0s and compare; split does it in one line
LeetCode 415: Add Strings
·2 mins
LeetCode Easy Math String Simulation
LeetCode 415 note: add digit by digit from the ends with two pointers, tracking the carry, and append any leftover carry after the loop
LeetCode 459: Repeated Substring Pattern
·1 min
LeetCode Easy String String-Matching Z-Algorithm Knuth-Morris-Pratt-Algorithm
LeetCode 459 note: s is a repetition of a substring exactly when s occurs in s + s with its first and last characters removed
LeetCode 482: License Key Formatting
·2 mins
LeetCode Easy String
LeetCode 482 note: remove every dash and uppercase first, then cut groups of k from the end so only the first group may be shorter