LeetCode Solutions

434. Number of Segments in a String

Time: $O(n)$

Space: $O(1)$

			

class Solution {
 public:
  int countSegments(string s) {
    int ans = 0;

    for (int i = 0; i < s.length(); ++i)
      if (s[i] != ' ' && (i == 0 || s[i - 1] == ' '))
        ++ans;

    return ans;
  }
};
			

class Solution {
  public int countSegments(String s) {
    int ans = 0;

    for (int i = 0; i < s.length(); ++i)
      if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' '))
        ++ans;

    return ans;
  }
}
			

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