-
Notifications
You must be signed in to change notification settings - Fork 0
/
2047. Number of Valid Words in a Sentence.cpp
91 lines (70 loc) · 2.16 KB
/
2047. Number of Valid Words in a Sentence.cpp
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
* problem link : https://leetcode.com/problems/number-of-valid-words-in-a-sentence/
* problem name: 2047. Number of Valid Words in a Sentence
* Status: Accepted.
* Author : Mohand sakr.
*/
class Solution {
public:
int countValidWords(string s) {
int len=s.length();
vector<string> vect;
while(s.length()>0){
int spacePlace=s.find(' ');
if(spacePlace!=-1){
string token=s.substr(0,spacePlace);
if(count(token.begin(),token.end(),' ')!=token.length())
{
vect.push_back(token);
}
s.erase(s.begin(),s.begin()+spacePlace+1);
}
else {
vect.push_back(s);
break;
}
}
int vectlen=vect.size();
int validWord=0;
for(int i=0;i<vectlen;i++){
if(isvalid(vect[i])){
++validWord;
}
}
return validWord;
}
bool isvalid(string s){
int len=s.length();
int count=0;
int hyphen =0;
for(int i=0;i<len;i++){
if(len==1){
if((s[i]>='a'&&s[i]<='z')||s[i]=='!'||s[i]=='.'||s[i]==',')
++count;
}
else {
if(!i){
if(s[i]>='a'&&s[i]<='z') ++count;
}
else if(i==len-1){
if((s[i]>='a'&&s[i]<='z') ||s[i]=='.'||s[i]==','||s[i]=='!'){
++count;
}
}
else {
if ((s[i]>='a'&&s[i]<='z')||
(s[i]=='-'&&(s[i-1]>='a'&&s[i-1]<='z')&&(s[i+1]>='a'&&s[i+1]<='z')))
{
if(s[i]=='-')
{
++hyphen;
}
++count;
}
}
}
}
if(hyphen>1) return 0;
return (count==len);
}
};