每日一题 0127
(2022.01.27) 每日一题 句子中有效单词数
简单题!但是我花了好大的劲。第一反应,切分判断,但是觉得好愚蠢。第二反应正则表达式,官方题解是遍历,但是我觉得太麻烦了,所以选择正则。
但是正则在cpp中有需要注意的点,因为之前使用python或者java写,只需要直接正则匹配即可。
注意点:
(1)cpp使用#include <regex>来使用正则表达式。其中使用过程如下:
//regex_match
//注意!!!!这是匹配的全文,顾名思义是一整个全部字符串,必须要符合你定义的模式,不然就匹配不了。匹配函数只有当模式匹配了整个字符串(或从给定位置开始的字符串),才会返回true。
bool regex_match(string s,regex pattern)
bool regex_match(string s,smatch result,regex pattern)
bool regex_match(s.cbegin()+i,s.cend(),smatch result,regex pattern)
//regex_search
//搜索给定字符串中是否存在与模式匹配的子串,如果存在则返回true。
bool regex_search(string s,regex pattern)
bool regex_search(string s,smatch result,regex pattern)
bool regex_search(s.cbegin()+i,s.cend(),smatch result,regex pattern)
//使用
regex pattern("[a-z]");
string s = "Hello";
bool ismatch = regex_match or regex_search(s,pattern);
//当字符串内有空格,我们要对每一个单词进行判断是否符合我们的模式时,可以使用istringstream
string s = "Hello World";
string temp;
for(istringstream iss(s);iss>>temp;){
std::cout<<temp<<std::endl; //会输出 Hello
// World ,istringstream会自动把空格去除。
bool ismatch = regex_match(s,pattern); #来判断字串是否符合我们的模式
}
最后题解如下:
class Solution {
public:
int countValidWords(string sentence) {
regex p("[a-z]*([a-z]+[-][a-z]+)?[a-z]*[.,!]?");
int res=0;
istringstream iss(sentence);
string temp;
while(iss>>temp){
bool ismatch= regex_match(temp,p);
if(ismatch){
res++;
}
}
return res;
}
};

浙公网安备 33010602011771号