leetcode-434-Number of Segments in a String

Topic description:

Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.

Please note that the string does not contain any non-printable characters.

Example:

Input: "Hello, my name is John"
Output: 5

 

Function to be done:

int countSegments(string s) 

 

illustrate:

This subject is fairly easy. A segment is defined as a continuous string that does not contain space characters, and it is required to return how many such segments are in a string.

Consider the boundary conditions, such as several consecutive space characters at the beginning, followed by "serious characters", such as ending with a space, and ending with no space.

code show as below:

    int countSegments(string s) 
    {
        int i=0,count=0;
        while(i<s.size())
        {
            if(s[i]==' ')
                i++; 
            else
            {
                count ++ ;
                 while (s[i]!= '  ' &&i< s.size())//The judgment condition here can also be replaced with
                    i++;            //s[i]!=' '&&s[i]!='\0'
            }
        }
        return count;
    }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324607223&siteId=291194637