[LeetCode] Number of Valid Words in a Sentence

2047. Number of Valid Words in a Sentence

A sentence consists of lowercase letters ('a' to 'z'), digits ('0' to '9'), hyphens ('-'), punctuation marks ('!', '.', and ','), and spaces (' ') only. Each sentence can be broken down into one or more tokens separated by one or more spaces ' '.

A token is a valid word if all three of the following are true:

  • It only contains lowercase letters, hyphens, and/or punctuation (no digits).
  • There is at most one hyphen '-'. If present, it must be surrounded by lowercase characters ("a-b" is valid, but "-ab" and "ab-" are not valid).
  • There is at most one punctuation mark. If present, it must be at the end of the token ("ab,", "cd!", and "." are valid, but "a!b" and "c.," are not valid).

Examples of valid words include "a-b.", "afad", "ba-c", "a!", and "!".

Given a string sentence, return the number of valid words in sentence.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
unordered_set<char> punch{'!','.',','};
bool check(string& s) {
if(s.length() == 0) return false;
if(punch.count(s.back())) s.pop_back();
for(int i = 0, fl = 0; i < s.length(); i++) {
if(punch.count(s[i])) return false;
if(isdigit(s[i])) return false;
if(s[i] == '-') {
if(i == 0 or i == s.length() - 1) return false;
if(islower(s[i-1]) and islower(s[i+1])) {
if(++fl == 2) return false;
} else return false;
} else if(!islower(s[i])) return false;
}
return true;
}
public:
int countValidWords(string s) {
s.push_back(' ');
int res = 0;
string now = "";
for(int i = 0; i < s.length(); i++) {
if(s[i] == ' ') {
if(check(now)) res += 1;
now = "";
} else now.push_back(s[i]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/02/09/PS/LeetCode/number-of-valid-words-in-a-sentence/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.