Skip to content

Latest commit

 

History

History
117 lines (90 loc) · 2.26 KB

File metadata and controls

117 lines (90 loc) · 2.26 KB

English Version

题目描述

统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。

请注意,你可以假定字符串里不包括任何不可打印的字符。

示例:

输入: "Hello, my name is John"
输出: 5
解释: 这里的单词是指连续的不是空格的字符,所以 "Hello," 算作 1 个单词。

解法

split 切分字符串,或者直接遍历计数。

Python3

class Solution:
    def countSegments(self, s: str) -> int:
        return len(s.split())
class Solution:
    def countSegments(self, s: str) -> int:
        res = 0
        for i in range(len(s)):
            if s[i] != ' ' and (i == 0 or s[i - 1] == ' '):
                res += 1
        return res

Java

class Solution {
    public int countSegments(String s) {
        int res = 0;
        for (String t : s.split(" ")) {
            if (!"".equals(t)) {
                ++res;
            }
        }
        return res;
    }
}
class Solution {
    public int countSegments(String s) {
        int res = 0;
        for (int i = 0; i < s.length(); ++i) {
            if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) {
                ++res;
            }
        }
        return res;
    }
}

C++

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

Go

func countSegments(s string) int {
	res := 0
	for i, c := range s {
		if c != ' ' && (i == 0 || s[i-1] == ' ') {
			res++
		}
	}
	return res
}

...