Java - Beats 100% - O(n) - Detailed solution


  • 0
    J

    Basically, every time we go from a character to an empty space, we know that is one word, so we increase the count.

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

Log in to reply
 

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