刀片服务器
Source and Knowledge
2025 年 5 月语言月赛,由洛谷网校提供。
简易字符串
文字题解
基础知识
【回文串判断】
对于字符串
可以使用两个指针
bool ispalindrome = true;
for(int l = 0, r = (int)s.size() - 1; l <= r; l++, r--) {
if(s[l] != s[r]) {
ispalindrome = false;
}
}
【子串提取】
string 类型提供了丰富的成员函数帮助我们完成字符串操作。其中,substr 成员函数可以用于提取子串。
substr 成员函数接受两个参数,第一个参数为起始提取的下标,第二个参数为提取的子串长度。如果提取的子串长度长于剩余的串长,则提取到字符串尾截止
提取字符串
string t = s.substr(l, r - l + 1);
通配回文
回到本题,首先,我们需要枚举所有的子串。这可以通过枚举子串的范围
子串提取后,需要判断其是否为回文串。本题引入了通配符 ?,但只需要在上文回文串判断代码中,修改匹配的判定逻辑即可。
if(s[l] != s[r] && s[l] != '?' && s[r] != '?') {
ispalindrome = false;
}