11-09字符串中的单词数

原题链接
在这里插入图片描述
解析:
方法一:

使用python直接进行分割,之后返回分割后的数量即可,时间16ms:

class Solution(object):
    def countSegments(self, s):
        """
        :type s: str
        :rtype: int
        """
        return len(s.split())

方法二:
使用c++的字符串进行操作,判断当前不是空格但下一个位置是空格,时间0ms:

class Solution {
    
    
public:
    int countSegments(string s) {
    
    
        s += ' ';
        int len = s.length();
        int cnt = 0;
        for(int i=0; i<len-1; i++)
        {
    
    
            if(s[i] != ' ' && s[i+1] == ' ')
                cnt++;
        }
        return cnt;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_45885232/article/details/109585594
今日推荐