Repeated_DNA_Sequences

题目描述:

  All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG".
  When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.
  Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule.
  (所有的DNA是由一系列的核苷酸组成,简称A,C,G,T,例如:“acgaattccg”。
   在研究DNA时,有时识别DNA中的重复序列十分有用。
   写一个函数来找到所有的10个字母的长序列(子)出现不止一次在一个DNA分子。)
For example,
Given s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT",

Return:
["AAAAACCCCC", "CCCCCAAAAA"].


思路:用0(00),1(01),2(10),3(11)来分别表示ACGT四种核苷酸,所以每十位核苷酸链用20位二进制码来表示(一个int类型的数32位)将每十位核苷酸构成的整数作为键来保存在hash表中,将其出现次数作为键所对应的值,当其出现次数大于一时则放入结果集中。其实重点在于位操作的处理。key = ((key<<2)|getValue(s.charAt(i))) & 0xfffff就是得到每十位核苷酸所构成的整数,先将原序列向左移两位这样该序列的最后两位均变为0与遍历到的核苷酸所代表的二进制数进行相或处理,那么最后两位就会变成遍历到的核苷酸的二进制数,例如"...CG",现在遍历到G,原序列"...01"向左移两位变为"...0100",与G所代表的二进制"10"进行相或处理,得到新序列"...0110",因为十位核苷酸只需要用20位二进制数来表示所以还要用0xfffff(转化为二进制就是前12位为0,后20位为一)将前12位都变为0就可以得到每十位核苷酸所构成的整数。

public class Repeated_DNA_Sequences {
	public static int getValue(char c)
	{
		if(c=='A')
			return 0;
		if(c=='C')
			return 1;
		if(c=='G')
			return 2;
		if(c=='T')
			return 3;
		return 4;
	}
	public static List<String> findRepeatedDnaSequences(String s) 
	{
		List<String> result = new ArrayList<String>();
		HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
		int key = 0;
		for(int i=0;i<s.length();i++)
		{
			key = ((key<<2)|getValue(s.charAt(i))) & 0xfffff;
//			System.out.println(key);
			if(i>=9)
			{
				if(map.get(key)==null)
				{
					map.put(key,1);
				}
				else
				{
					if(map.get(key)==1)
					{
						result.add(s.substring(i-9,i+1));
						map.put(key,Integer.MAX_VALUE);
					}
				}
			}
		}
		return result;
    }
	public static void main(String[] args) {
		String s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT";
		List<String> result = findRepeatedDnaSequences(s);
		System.out.println(result.size());
		for(int i=0;i<result.size();i++)
		{
			System.out.println(result.get(i));
		}
	}
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值