统计字符串片段,两种方法,比较简单,不做解释,代码如下:
第一种,利用标志位
1 class Solution { 2 public: 3 int countSegments(string s) { 4 int count=0; 5 bool space=true; 6 for(int i=0;i<s.size();i++){ 7 if(space==true&&s[i]!=' '){ 8 count++; 9 space=false; 10 } 11 else if(s[i]==' '){ 12 space=true; 13 } 14 } 15 return count; 16 } 17 };
第二种,两个字符判定,满足前一个字符非空格,后一个字符空格,才增加计数器
1 static int wing=[]() 2 { 3 std::ios::sync_with_stdio(false); 4 cin.tie(NULL); 5 return 0; 6 }(); 7 8 class Solution 9 { 10 public: 11 int countSegments(string s) 12 { 13 int len=s.length(); 14 if(len<1) 15 return 0; 16 int count=0; 17 int i; 18 for(i=0;i<len-1;i++) 19 { 20 if(s[i]!=' '&&s[i+1]==' ') 21 count++; 22 } 23 if(s[i]!=' ') 24 count++; 25 return count; 26 } 27 };
浙公网安备 33010602011771号