Clean java solution O(n)


  • 47
    A
    public int countSegments(String s) {
        int res=0;
        for(int i=0; i<s.length(); i++)
            if(s.charAt(i)!=' ' && (i==0 || s.charAt(i-1)==' '))
                res++;        
        return res;
    }
    
    Time complexity:  O(n)
    Space complexity: O(1)

  • 0
    F

    @asurana28 great! one line in python using the same idea:

        def countSegments(self, s):
            return sum([s[i] != ' ' and (i == 0 or s[i - 1] == ' ') for i in range(len(s))])
    
        def countSegments(self, s):
            return sum(map(lambda i: s[i] != ' ' and (i == 0 or s[i - 1] == ' '), range(len(s))))
    

  • 1

    Great solution, just increment the count on the first character of each word.
    One tweak - handle the index zero case outside your loop, where you initialize count.

        public int CountSegments(string s) 
        {
            if (s.Length == 0) return 0;
            int count = s[0] != ' ' ? 1 : 0;
            for (int i = 1; i < s.Length; i++)
            {
                // count the number of word starts
                count += s[i] != ' ' && s[i-1] == ' ' ? 1 : 0;  
            }
            return count;
        }
    

  • 0
    A

    class Solution
    {
    public:
    int countSegments(string s)
    {
    stringstream ss(s);
    string temp;
    int count = 0;

        while(getline(ss,temp,' '))
        {
            if(!temp.empty())
                count++;
        }
            
        return count;
    }
    

    };


  • 0

    nice solution


  • 1
    C

    Alternate Solution just for reference. The Original Solution by the Author is much faster, However the time complexity and space complexity is same.

    public int countSegments(String s) {
        s=s.trim();
        if(s.length()==0){
            return 0;
        }
        return s.split("\\s+").length;
        
    }
    

  • 0
    W
    This post is deleted!

  • 0
    G

    i did a little modification

     public  int countSegments(String s){
            int cnt = 0;
            s = ' '+s;
            for(int i=1;i<s.length();i++){
                if(s.charAt(i)!=' ' && s.charAt(i-1)==' ')
                    cnt++;
            }
            return cnt;
        }
    }
    

    inspired from StefanPochmann solution


  • 0
    G

    @asurana28 Two lines Java with explation:
    First: if s=" *",then return 0
    Second: remove space from front and back,then split(" +"),count the length of the new String[],so this is my 2 lines code:
    java

    public class Solution {
        public int countSegments(String s) {
            if(s.matches(" *"))return 0;
            return s.trim().split(" +").length;
        }
    }
    

    and one line python:

     return len(s.split())
    

  • 0
    H

    my solution, easy to understand

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

  • 0
    G

    @chintant How could u say space complexiity is same as when,
    s=s.trim() || s= s.replaceAll(" \s+"," ");
    Aren't they kindaa creating a new string with replaced spaces????


  • 0
    V

    Simple Java Solution :

    class Solution {
        public int countSegments(String s) 
        {
        		if (s.length() == 0) return 0;
        		int count  = 0;
        		String [] str = s.split(" ");
        		
        		for (int i = 0; i<str.length;i++)
        		{
        			if (!str[i].matches(""))
        			{
        				count++;
        			}
        		}
        		return count;
                    
        }
    }
    

Log in to reply
 

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