2047.句子中的有效单词数
链接:2047.句子中的有效单词数
难度:Easy
标签:字符串
简介:给你一个字符串 sentence ,请你找出并返回 sentence 中 有效单词的数目 。
题解 1 - cpp
- 编辑时间:2022-01-27
- 执行用时:4ms
- 内存消耗:7MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
   public:
    string str;
    int idx = 0;
    void scan_blank() {
        while (idx < str.size() && str[idx] == ' ') idx++;
    }
    int check(int start, int end) {
        if (start == end) return 0;
        int cnt_line = 0, cnt_tag = 0;
        for (int i = start; i < end; i++) {
            char ch = str[i];
            if (ch == '-') {
                if (++cnt_line > 1 || i == start || i == end - 1 ||
                    str[i - 1] < 'a' || str[i - 1] > 'z' || str[i + 1] < 'a' ||
                    str[i + 1] > 'z')
                    return 0;
            } else if (ch == '!' || ch == '.' || ch == ',') {
                if (++cnt_tag > 1 || i != end - 1) return 0;
            } else if (ch < 'a' || ch > 'z')
                return 0;
        }
        return 1;
    }
    int countValidWords(string sentence) {
        str = sentence;
        int ans = 0;
        do {
            scan_blank();
            int start = idx, end = idx;
            while (end < str.size() && str[end] != ' ') end++;
            idx = end;
            if (check(start, end)) ans++;
        } while (idx < str.size());
        return ans;
    }
};