题解 | #密码截取#
密码截取
https://www.nowcoder.com/practice/3cd4621963e8454594f00199f4536bb1
#include <iostream>
#include <string>
using namespace std;
class Password {
private:
string s;
public:
//构造函数
Password(const string s);
//析构函数
~Password();
//判断是否是对称子串
bool isSymSubStr(const int begin, const int end)const;
//返回有效密码串的最大长度
int maxLenOfValidCipherStr(void)const;
};
Password::Password(const string s) {
this->s = s;
return;
}
Password::~Password() {
}
bool Password::isSymSubStr(const int begin, const int end)const {
//同步缩短首尾,如果第一个字符始终与最后一个字符相同,则子串对称
for (int i = begin, j = end; i < j; i++, j--)
if (this->s[i] != this->s[j])
return false;
return true;
}
int Password::maxLenOfValidCipherStr(void)const {
//遍历所有可能性,将最大值返回
int maxlength = 0;
for (int i = 0; i < this->s.size(); i++)
for (int j = this->s.size(); j > i; j--)
if (this->isSymSubStr(i, j))
if (maxlength < j - i + 1)
maxlength = j - i + 1;
return maxlength;
}
int main() {
string s;
while (cin >> s) { // 注意 while 处理多个 case
Password p(s);
cout << p.maxLenOfValidCipherStr() << endl;
}
}
// 64 位输出请用 printf("%lld")
