题目描述
小艺酱想给自己起一个英文名字。 小艺酱想要装的自己学识渊博。 所以她想要自己英文名字必须满足:
1.只有字母表中前k个小写字母。
2.必须是回文串。
3.前k个小写字母每个字母至少出现一次。
小艺酱已经自己完成了部分空余的字母部分用’?’代替。
请你帮她完成她的英文名字。
输入描述:
第一行输入一个整数k。(1<=k<=26) 第二行输入小艺酱的英文名字name。(1<=strlen(name)<=1000)
输出描述:
如果小艺的名字不存在输出“QAQ”, 如果存在多组解,输出字典序最小的一个解。
代码实现:
/**
* 小艺的英文名
* 1.只有字母表中前k个小写字母。
* 2.必须是回文串。
* 3.前k个小写字母每个字母至少出现一次。
* 4.如果存在多组解,输出字典序最小的一个解
* @param k
* @param name
* @return
*/
public static String solution(int k, String name){
String result = "";
// TODO: 请在此编写代码
if(k<1 || (null == name || name.length() == 0) ){
return result;
}
//获取前k个小写字母
List<Character> kList = getChar(k);
//已存在的小写字母
List<Character> exsitList = transStrToList(name);
//回文体,中心对称,eg: 奇数长度 aba , 偶数长度 abba
int count = exsitList.size();
//是否为偶数
boolean flag = count%2 == 0;
int twoSplit = flag ? count/2 : count/2 +1;
//前k个小写字母每个字母至少出现一次,不符合则返回 :""
if(twoSplit < k){
return result;
}
Character repStr = '?';
//判断串里是否只包含前k个小写字母
Set<Character> tempSet = new HashSet<>();
tempSet.addAll(exsitList);
tempSet.removeAll(kList);
tempSet.remove(repStr);
//存在不为前k字母的字符,不符合要求,返回空串
if(tempSet.size()>0){
return result;
}
//获取未使用的字符列表
kList.removeAll(exsitList);
//判断是否为回文串
boolean isCycle = true;
for(int i=0;i<twoSplit;i++){
boolean kflag = kList.size() > 0;
Character c = exsitList.get(i);
// 如果字符串为奇数位
if(i == twoSplit-1 && !flag){
//为替代符,则将最低序字符给
if(c == repStr ){
if(kflag){
exsitList.set(i,kList.get(0));
kList.remove(0);
} else {
// 字符已用完,补充最小字典序 a
exsitList.set(i,'a');
}
}
break;
}
// 和 c 对称位置 的字符
int crIndex = count - i - 1;
Character cr = exsitList.get(crIndex);
if(c == cr ){
if(c == repStr ){
// 存在未用的字符
if(kflag){
exsitList.set(i,kList.get(0));
exsitList.set(crIndex,kList.get(0));
kList.remove(0);
} else {
// 字符已用完,补充最小字典序 a
exsitList.set(i,'a');
exsitList.set(crIndex,'a');
}
}
} else {
// 判断是否为回文串
if(c != repStr && cr != repStr){
isCycle = false;
break;
}
if(c == repStr){
exsitList.set(i,cr);
} else {
exsitList.set(crIndex,c);
}
}
}
//如果不是回文串,返回空串
if(!isCycle){
return result;
}
// 如何还有未用字符,则不符合最少出现一次要求,返回空串
if(kList.size()>0){
return result;
}
//转化成字符串
for(Character cha : exsitList){
result +=cha.toString();
}
return result;
}
private String reverse(String str){
return str;
}
/**
* 获取前k个小写字母
* 最大输出26个小写英文字母
* @param k
* @return
*/
private static List<Character> getChar(int k){
List<Character> list = new ArrayList<>();
if(k<1){
return list;
}
if(k>26){
k=26;
}
list.add('a');
for(int i=1;i<k;i++){
list.add((char)('a'+i));
}
return list;
}
/**
* 字符串转列表
* @param name
* @return
*/
private static List<Character> transStrToList(String name){
List<Character> list = new ArrayList<>();
if(null == name || "".equals(name)){
return list;
}
for(int i=0;i<name.length();i++){
list.add(name.charAt(i));
}
return list;
}
结果:
运行成功:
不通过
您的代码已保存。
答案错误,您提交的程序没有通过所有的测试用例。
case通过率:50.0%
疑问:
代码检查,自我感觉已覆盖所有要求,不知道哪里出现问题,请哪位大神帮忙检查一下