题目
类型:字符串
解题思路
先将 sentence 按照空格进行分割,得到多个 item,再对每个 item 进行合法性检查,最后统计合法的 item 个数即为答案
在对 item 进行合法性检查时,分别使用 c1 和 c2 代表「连字符」和「标点符号」的出现次数。
代码
class Solution {
public int countValidWords(String sentence) {
String[] ss = sentence.split(" ");
int ans = 0;
for (String s : ss) if (check(s)) ans++;
return ans;
}
boolean check(String s) {
int n = s.length();
if (n == 0) return false;
for (int i = 0, c1 = 0, c2 = 0; i < n; i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) return false;
if (c == ' ') return false;
if (c == '-' && ++c1 >= 0) {
if (c1 > 1 || (i == 0 || i == n - 1)) return false;
if (!Character.isLetter(s.charAt(i - 1)) || !Character.isLetter(s.charAt(i + 1))) return false;
}
if ((c == '!' || c == '.' || c == ',') && ++c2 >= 0) {
if (c2 > 1 || (i != n - 1)) return false;
}
}
return true;
}
}