Java Solution. O(1) Space Complexity, 2ms


  • 0
    E
    public class Solution {
        public int countSegments(String s) {
            s = s.trim();
            if(s.length() == 0) return 0;
            int count = 1;
           
            for(int i = 0; i + 1 < s.length(); i++)
              if(s.charAt(i) == ' ' && s.charAt(i + 1) != ' ')
                count++;
                  
              return count;  
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.