原题链接:https://leetcode-cn.com/problems/number-of-valid-words-in-a-sentence/
class Solution {
public:
int countValidWords(string sentence) {
int t = 0, n = sentence.size(), res = 0;
while (t < n && sentence[t] == ' ') {
t++;
}
while (t < n) {
map<char, int> mp;
int i = t;
int j = t;
while (j < n && sentence[j] != ' ') {
j++;
}
t = j;
while (t < n && sentence[t] == ' ') {
t++;
}
while (i < j) {
char c = sentence[i];
if (isdigit(c)) {
break;
} else if (!isalpha(c)) {
if (mp.count(c)) {
break;
} else if (c == '-') {
if (i != 0 && i < j - 1 && isalpha(sentence[i - 1]) && isalpha(sentence[i + 1])){
mp[c] = 1;
} else {
break;
}
} else if (i != j - 1) {
break;
}
}
i++;
}
if (i == j) {
res++;
}
}
return res;
}
};
|