列表

详情


2047. 句子中的有效单词数

句子仅由小写字母('a''z')、数字('0''9')、连字符('-')、标点符号('!''.'',')以及空格(' ')组成。每个句子可以根据空格分解成 一个或者多个 token ,这些 token 之间由一个或者多个空格 ' ' 分隔。

如果一个 token 同时满足下述条件,则认为这个 token 是一个有效单词:

这里给出几个有效单词的例子:"a-b.""afad""ba-c""a!""!"

给你一个字符串 sentence ,请你找出并返回 sentence 有效单词的数目

 

示例 1:

输入:sentence = "cat and  dog"
输出:3
解释:句子中的有效单词是 "cat"、"and" 和 "dog"

示例 2:

输入:sentence = "!this  1-s b8d!"
输出:0
解释:句子中没有有效单词
"!this" 不是有效单词,因为它以一个标点开头
"1-s" 和 "b8d" 也不是有效单词,因为它们都包含数字

示例 3:

输入:sentence = "alice and  bob are playing stone-game10"
输出:5
解释:句子中的有效单词是 "alice"、"and"、"bob"、"are" 和 "playing"
"stone-game10" 不是有效单词,因为它含有数字

 

提示:

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class Solution { public: int countValidWords(string sentence) { } };

golang 解法, 执行用时: 4 ms, 内存消耗: 2.7 MB, 提交时间: 2023-09-27 14:58:06

func valid(s string) bool {
    hasHyphens := false
    for i, ch := range s {
        if unicode.IsDigit(ch) || strings.ContainsRune("!.,", ch) && i < len(s)-1 {
            return false
        }
        if ch == '-' {
            if hasHyphens || i == 0 || i == len(s)-1 || !unicode.IsLower(rune(s[i-1])) || !unicode.IsLower(rune(s[i+1])) {
                return false
            }
            hasHyphens = true
        }
    }
    return true
}

func countValidWords(sentence string) (ans int) {
    for _, s := range strings.Fields(sentence) { // 按照空格分割
        if valid(s) {
            ans++
        }
    }
    return
}

javascript 解法, 执行用时: 72 ms, 内存消耗: 45.2 MB, 提交时间: 2023-09-27 14:57:52

/**
 * @param {string} sentence
 * @return {number}
 */
var countValidWords = function(sentence) {
    const n = sentence.length;
    let l = 0, r = 0;
    let ret = 0;
    while (true) {
        while (l < n && sentence[l] === ' ') {
            l++;
        }
        if (l >= n) {
            break;
        }
        r = l + 1;
        while (r < n && sentence[r] != ' ') {
            r++;
        }
        if (isValid(sentence.slice(l, r))) { // 判断根据空格分解出来的 token 是否有效
            ret++;
        }
        l = r + 1;
    }
    return ret;
};

const isValid = (word) => {
    const n = word.length;
    let hasHyphens = false;
    for (let i = 0; i < n; i++) {
        if (word[i] >= '0' && word[i] <= '9') {
            return false;
        } else if (word[i] === '-') {
            if (hasHyphens === true || i === 0 || i === n - 1 || !isLetter(word[i - 1]) || !isLetter(word[i + 1])) {
                return false;
            }
            hasHyphens = true;
        } else if (word[i] === '!' || word[i] === '.' || word[i] === ',') {
            if (i !== n - 1) {
                return false;
            }
        }
    }
    return true;
}

const isLetter = (ch) => {
    if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') {
        return true;
    }
    return false;
}

java 解法, 执行用时: 3 ms, 内存消耗: 40.7 MB, 提交时间: 2023-09-27 14:57:32

class Solution {
    public int countValidWords(String sentence) {
        int n = sentence.length();
        int l = 0, r = 0;
        int ret = 0;
        while (true) {
            while (l < n && sentence.charAt(l) == ' ') {
                l++;
            }
            if (l >= n) {
                break;
            }
            r = l + 1;
            while (r < n && sentence.charAt(r) != ' ') {
                r++;
            }
            if (isValid(sentence.substring(l, r))) { // 判断根据空格分解出来的 token 是否有效
                ret++;
            }
            l = r + 1;
        }
        return ret;
    }

    public boolean isValid(String word) {
        int n = word.length();
        boolean hasHyphens = false;
        for (int i = 0; i < n; i++) {
            if (Character.isDigit(word.charAt(i))) {
                return false;
            } else if (word.charAt(i) == '-') {
                if (hasHyphens == true || i == 0 || i == n - 1 || !Character.isLetter(word.charAt(i - 1)) || !Character.isLetter(word.charAt(i + 1))) {
                    return false;
                }
                hasHyphens = true;
            } else if (word.charAt(i) == '!' || word.charAt(i) == '.' || word.charAt(i) == ',') {
                if (i != n - 1) {
                    return false;
                }
            }
        }
        return true;
    }
}

cpp 解法, 执行用时: 8 ms, 内存消耗: 7.1 MB, 提交时间: 2023-09-27 14:57:19

class Solution {
public:
    int countValidWords(string sentence) {
        int n = sentence.length();
        int l = 0, r = 0;
        int ret = 0;
        string_view slice(sentence);
        while (true) {
            while (l < n && sentence[l] == ' ') {
                l++;
            }
            if (l >= n) {
                break;
            }
            r = l + 1;
            while (r < n && sentence[r] != ' ') {
                r++;
            }
            if (isValid(slice.substr(l, r - l))) { // 判断根据空格分解出来的 token 是否有效
                ret++;
            }
            l = r + 1;
        }
        return ret;
    }

    bool isValid(const string_view &word) {
        int n = word.length();
        bool has_hyphens = false;
        for (int i = 0; i < n; i++) {
            if (word[i] >= '0' && word[i] <= '9') {
                return false;
            } else if (word[i] == '-') {
                if (has_hyphens == true || i == 0 || i == n - 1 || !islower(word[i - 1]) || !islower(word[i + 1])) {
                    return false;
                }
                has_hyphens = true;
            } else if (word[i] == '!' || word[i] == '.' || word[i] == ',') {
                if (i != n - 1) {
                    return false;
                }
            }
        }
        return true;
    }
};

python3 解法, 执行用时: 52 ms, 内存消耗: 16 MB, 提交时间: 2023-09-27 14:57:03

class Solution:
    def countValidWords(self, sentence: str) -> int:
        def valid(s: str) -> bool:
            hasHyphens = False
            for i, ch in enumerate(s):
                if ch.isdigit() or ch in "!.," and i < len(s) - 1:
                    return False
                if ch == '-':
                    if hasHyphens or i == 0 or i == len(s) - 1 or not s[i - 1].islower() or not s[i + 1].islower():
                        return False
                    hasHyphens = True
            return True

        return sum(valid(s) for s in sentence.split())

python3 解法, 执行用时: 40 ms, 内存消耗: 15 MB, 提交时间: 2022-07-06 11:25:43

class Solution:
    def countValidWords(self, sentence: str) -> int:
        p = re.compile(r'(?:(?<=\s)|(?<=^))([a-z]+\-[a-z]+|[a-z]+)?(?(1)[\!\,\.]?|[\!\,\.])(?:(?=\s)|(?=$))')
        return len(p.findall(sentence))

上一题