基因序列

基因序列可以由A,G,C,U四个字母组成的序列表示,某科学家想通过向给定的基因序列中
插入字母使得序列前后对称来进行研究
你的任务是:
给定一个基因序列,计算一下要插入多少个字母才能使得序列前后对称。
输入一行,表示带插入的基因序列(长度不大于1000)
要求输出一个正整数,表示至少要插入多少个字母。

package the_blue_cup;
//密码脱落
import java.util.Scanner;

public class Demo_12 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		String characterString = sc.nextLine();
		
		System.out.println(findCode(characterString));
		
	}
	//该方法返回最少字母缺失个数
	public static int findCode(String string) {
		char[] characterList = string.toCharArray();//将字符串转化为数组
		//初始化计数
		int count = 0;
		//分别从两头往中间寻找相同字母,并计数
		int leftCount, rightCount;
		从两边开始遍历,
		for (int i = 0, j = characterList.length - 1; i < j;) {//迭代后操作写在循环内部
			//若对应值相等
			if (characterList[i] == characterList[j]) {
				i++;
				j--;
				continue;//跳出本次循环
			}else {
				//若对应值不相等
				leftCount = 0;//左侧计数初始化为0
				int leftCursor = i;//创建一个指针变量从该索引处往右寻找
				
				while(characterList[leftCursor] != characterList[j]) {
					leftCursor++;//不相等指针向前移动
					leftCount++;//并计数
				}
				//类似
				rightCount = 0;
				int rightCursor = j;
				while(characterList[rightCursor] != characterList[i]) {
					rightCursor--;//向左侧移动
					rightCount++;//并计数
				}
				//将最短路径赋给对应变量
				if (leftCount > rightCount) {
					j -= rightCount;
				}else {
					i += leftCount;
				}
				//计算最短路径
				count += (leftCount < rightCount) ? leftCount : rightCount;
			}
		}
			
		return count;
	}

}


你可能感兴趣的:(基因序列)