题解 | #牛群密码 - 有效回文#
牛群密码 - 有效回文
https://www.nowcoder.com/practice/98fad63b47544d5ebf4042fc53b54b3d
#include <string>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param password string字符串
* @param k int整型
* @return bool布尔型
*/
//去除某一个字符后的字符串
string newstring(string s,int n){
int num = s.length();
if(n >= num){
return"";
}
string res;
if(n == 0){
for(int i = 1; i < num; i++){
res.push_back(s[i]);
}
}else if(n == num - 1){
for(int i = 0; i < num-1; i++){
res.push_back(s[i]);
}
}else{
for(int i = 0; i < n; i++){
res.push_back(s[i]);
}
for(int i = n + 1; i < num; i++){
res.push_back(s[i]);
}
}
return res;
}
//判断字符串是否为回文串
bool isPalindrome(string s){
if(s.length() <= 2){
return true;
}
for(int i = 0, j = s.length() - 1; i < s.length(), j >= 0; i++, j--){
if(s[i] != s[j]){
return false;
}
}
return true;
}
bool isValidPalindrome(string password, int k) {
// write code here
//判断字符串中字符种类数是否满足条件
string ss = password;
sort(ss.begin(),ss.end());
int num = ss.length();
//count为字符种类数目,cc为去除其中一个字符后的字符串为回文串的数目
int count = 0,cc = 0;
for(int i = 0; i < num - 1; i++){
if(ss[i] != ss[i+1]){
count++;
}
}
if(count > k){
return false;
}else{
for(int i = 0; i < num; i++){
string temp = "";
int n = i;
temp = newstring(password, n);
if(isPalindrome(temp)){
cc++;
}
}
}
return cc != 0;
}
};
