434. Number of Segments in a String ¶ Time: $O(n)$ Space: $O(1)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12class 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; } }; 1 2 3 4 5 6 7 8 9 10 11class 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; } } 1 2 3class Solution: def countSegments(self, s: str) -> int: return len(s.split())