给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。

如果不存在最后一个单词,请返回 0 。

说明:一个单词是指由字母组成,但不包含任何空格的字符串。

示例:

输入: "Hello World"
输出: 5

int lengthOfLastWord(char* s) {
    unsigned int flag = 0;
    unsigned int count = 0;
    
    if(*s==NULL)
        return 0;
    while(*s != NULL)
    {
        if((*s == ' ')&&(*(s+1)!=' ')&&(*(s+1)!=NULL))
        {
            flag = 1;
            count = 0;
            
        }
        if((flag = 1)&&(*s!=' '))
        {
            count++;
                
            
        }
        if((*s!=' ')&&(*(s+1)==' '))
        {
            flag = 0;
        }
        s++;
    }
        
        
      return count;  
    
    
}

解题思路:flag是一个预flag 当遇到发现了一个空格 且后面不是空格或者NULL的时候打开

                当连续空格的时候关闭Flag 

 

 

还有一种更快的方法如下:

 

int lengthOfLastWord(char* s) {
   
    int prec = 0;
    int nowc = 0;
    int count = 0;
    while(*s!=NULL)
    {   
       
        if(*s==' ')
        {count!=0?prec = count:0; count=0;}
         else
         {count++;}
        s++;
        
    }
        
  return count>0?count:prec;      
}

 

posted on 2019-06-11 11:57  闲云潭影  阅读(103)  评论(0编辑  收藏  举报