第五届在线编程大赛月赛指定题目:反向互

lvs007 lvs007 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
这是个字符串问题。我们的字符串只包含大写字母。我们定义一个字母和它13位以后的字母互补。即A与N互补,B与O互补,C与P互补……,我们需要找一个字符串的两个不重叠的子串,其中一个和另外一个的翻转全互补。另外,因为我们的问题来自生物学,所以我们允许这两个字符串的一个可以删掉两个字符(注意:仅允许一个字符串删掉任意位置的两个字符,另外一个必须全部互补上)。我们的目的是求最长的反向互补子串的长度。 输入格式: 多组数据,每组数据一行,有一个字符串。每个字符串长度不超过2000,只有大写英文字母组成。 输出格式: 每组数据输出一行包含一个整数,表示最长的反向互补子串长度。
挑战规则:
输入样例 ABCD ABCDQOPN ABON 输出样例: 0 2 2 解释: 第一个样例,没有互补的子串。 第二个样例,AB和NO互补,所以反向互补子串的时候我们可以选择NPO,删掉一个P即可。 第三个样例,AB与ON反向互补。


个人代码:

import java.util.LinkedList;
import java.util.Queue;

public class StringBewteen {

public static int find(String str){
char[] ch = str.toCharArray();
int length = ch.length;
int i = 0;
int max = 0;
while(i<length){
int result = analyze(ch, i);
if(max<result){
max = result;
}
++i;
}
return max;
}

public static int analyze(char[] ch,int start){
char begin = ch[start];
Queue<Integer> queue = new LinkedList<Integer>();
int max = 0;
int max_1 = 0;
int max_2 = 0;
for(int i = start+1;i<ch.length;i++){
if(begin+13 == ch[i] || begin-13 == ch[i]){
queue.add(i);
}
}
if(queue.isEmpty()){
return 0;
}

int result = 0;
int result_1 = 0;

for(int n : queue){

int bet = start;
int bet_1 = start;
int bet_2 = start;
int n_1 = n;
int n_2 = n;
max = 1;
max_1 = 1;
max_2 = 1;

while(++bet<ch.length && --n>bet){
// System.out.println("n="+n+" bet="+bet);
if(ch[bet]+13 == ch[n] || ch[bet]-13 == ch[n]){
++max;
}else{
break;
}
}
int tmp = 0;
while(++bet_1<ch.length && --n_1>bet_1){
// System.out.println("n_1="+n_1+" bet_1="+bet_1);
if(ch[bet_1]+13 == ch[n_1] || ch[bet_1]-13 == ch[n_1]){
++max_1;
}else{
if(tmp<2){
--bet_1;
}else{
break;
}
++tmp;
}
}
tmp = 0;
while(++bet_2<ch.length && --n_2>bet_2){
// System.out.println("n_2="+n_2+" bet_2="+bet_2);
if(ch[bet_2]+13 == ch[n_2] || ch[bet_2]-13 == ch[n_2]){
++max_2;
}else{
if(tmp<2){
++n_2;
}else{
break;
}
++tmp;
}
}
result_1 = max > max_1?(max>max_2?max:max_2):(max_1>max_2?max_1:max_2);

if(result < result_1){
result = result_1;
}
}
// System.out.println("max="+max+"\t max_1="+max_1+"\t max_2="+max_2);

return result;
}

public static void main(String[] args) {
String[] str = args;
if(str == null || str.length == 0){
str = new String[]{"ABCDQOPNXAFADNSSNABON","ABCD","ABCDQOPN","ABON"};
}
for(int i=0;i<str.length;i++){
System.out.println("find = "+find(str[i]));
}
}
}

求大牛看一下有什么错误吗?我感觉没有错误啊!!!
...全文
评论 4
收藏 已收藏
分享
返回顶部
lvs007
Java 51,407 成员 86,128 内容