[
string
two pointers
]
Leetcode 0434 Number of Segments in a String
Problem statement
https://leetcode.com/problems/number-of-segments-in-a-string/
Solution
That is what exactly function .split()
will do, we just need to find number of parts.
Complexity
It is O(n)
for time and space.
Code
class Solution:
def countSegments(self, s):
return len(s.split())
Remark
If split()
is not allowed, we can use two pointers approach with O(n)
time and O(1)
space or we can use only one pointer and find number of places i
, for which which s[i-1]
is space or i = 0
and s[i]
is not space.