Fork me on GitHub

[leetcode-434-Number of Segments in a String]

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

思路:

从头到尾遍历,如果是空格,直接跳过。

非空格字符都遍历完后,segment++。

int countSegments(string s)
     {
         int seg = 0;
         int len = s.length();
         for (int i = 0; i < len;)
         {
             while (i < len && s[i] == ' ')i++;//去掉空格
             if (i>=len) break;              
             while (i < len && s[i] != ' ')i++;
             seg++;            
         }

         return seg;
     }

 

posted @ 2017-06-12 20:17  hellowOOOrld  阅读(121)  评论(0编辑  收藏  举报