题目:2047. 句子中的有效单词数
思路:按题意要求来判断字符串即可
class Solution {
public:
bool check(string s){
int ct1=0;
for(int i=0;i<s.size();i++){
if(s[i]>='0'&&s[i]<='9'){
return 0;
}else if(s[i]=='-'){
if(ct1!=0){
return 0;
}
if(i==0||i==s.size()-1){
return 0;
}
if(s[i-1]>='a'&&s[i-1]<='z'&&s[i+1]>='a'&&s[i+1]<='z'){
ct1++;
continue;
}else{
return 0;
}
}else if(s[i]=='.'||s[i]=='!'||s[i]==','){
if(i!=s.size()-1) return 0;
}
}
cout<<s<<endl;
return 1;
}
int countValidWords(string sentence) {
int ans=0;
string t="";
for(auto x:sentence){
if(x==' '&&t!=""){
if(check(t)) ans++;
t="";
}else if(x!=' '){
t.push_back(x);
}
}
if(t!=""){
if(check(t)) ans++;
}
return ans;
}
};