LeetCode 2047. 句子中的有效单词数

2047. 句子中的有效单词数

Solution

思路:简单模拟题,首先将单词划分开,然后根据条件一个一个否定即可。标记连接符和标点符号的位置,进行判断,这里注意特判是在数值为1的时候做的。

class Solution {
    public int countValidWords(String sentence) {
        String[] words = sentence.split(" ");
        int cnt = 0;
        for (String str : words) {
            if (str.length() == 0) continue;
            int cntNum = 0;
            int cntLink = 0, posLink = -1;
            int cntPunc = 0, posPunc = -1;
            int len = str.length();
            for (int i = 0; i < len; i++) {
                if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
                    cntNum++;
                } else if (str.charAt(i) == '-') {
                    cntLink++;
                    posLink = i;
                } else if (str.charAt(i) == '!' || str.charAt(i) == '.' || str.charAt(i) == ',') {
                    cntPunc++;
                    posPunc = i;
                }
            }
            if (cntNum > 0) continue;
            if (cntLink > 1) continue;
            if (cntLink == 1) {
                if (posLink == 0 || posLink == len - 1) continue;
                if (str.charAt(posLink - 1) < 'a' || str.charAt(posLink - 1) > 'z') continue;
                if (str.charAt(posLink + 1) < 'a' || str.charAt(posLink + 1) > 'z') continue;
            }
            if (cntPunc > 1) continue;
            if (cntPunc == 1) {
                if (posPunc != len - 1) continue;
            }
            cnt++;
        }
        return cnt;
    }
}
posted @ 2022-01-27 20:47  Frontierone  阅读(22)  评论(0编辑  收藏  举报