leetcode_Repeated DNA Sequences
2015-08-12 09:56
302 查看
描述:
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.
For example,
Given s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT", Return: ["AAAAACCCCC", "CCCCCAAAAA"].
思路:
1.很显然,暴力求解也是一种方法,尽管该方法是不可能的。2.我们首先来看字母 ”A" "C" “G" "T" 的ASCII码,分别是65, 67, 71, 84,二进制表示为 1000001, 1000011, 1000111, 1010100。可以看到它们的后三位是不同,所以用后三位就可以区分这四个字母。一个字母用3bit来区分,那么10个字母用30bit就够了。用int的第29~0位分表表示这0~9个字符,然后把30bit转化为int作为这个子串的key,放入到HashTable中,以判断该子串是否出现过。
代码:
public List<String> findRepeatedDnaSequences(String s) { List<String>list=new ArrayList<String>(); int strLen=s.length(); if(strLen<=10) return list; HashMap<Integer, Integer>map=new HashMap<Integer,Integer>(); int key=0; for(int i=0;i<strLen;i++) { key=((key<<3)|(s.charAt(i)&0x7))&0x3fffffff;//k<<3,key左移3位,也就是将最左边的字符移除 //s.charAt(i)&0x7)获得用于标记s.charAt(i)字符的低3位 //&0x3fffffff抹去key左移三位后多出的高位不相关比特位 if(i<9)continue; if(map.get(key)==null)//如果没有该整数表示的字符串,将其添加进map中 map.put(key, 1); else if(map.get(key)==1)//如果存在,说明存在重复字符串并将其添加进结果list中 { list.add(s.substring(i-9,i+1)); map.put(key, 2);//防止重复添加相同的字符串 } } return list; }
相关文章推荐
- Purpose of requirePermission attribute (web.config)
- easyui学习笔记2:页面布局,layout插件
- IOS UILabel 详解
- Android详细的对话框AlertDialog.Builder使用方法
- easyui学习笔记1:搭建环境,编写hellworld
- 【POJ】 2442——Sequence【STL—优先队列】
- [LeetCode]Repeated DNA Sequence
- 关于iOS 7以后自定义UIAlertview(CustomIOS7AlertView)的用法心得
- UGUI 扩展集
- Xcode 学习之路 Interface Builder使用技巧
- NHibernate3剖析:Query篇之NHibernate.Linq增强查询
- NHibernate3剖析:Query篇之NHibernate.Linq自定义扩展
- requirejs 跨域
- iOS-Core-Animation-Advanced-Techniques 中文翻译
- UIBezierPath 和 CAShapeLayer 绘画图纸
- Android API Guides –Device Compatibility
- HDOJ-1503-Advanced Fruits
- 给EasyUI的DateBox控件添加清除button
- 关于4.6.x版本的UGUI的学习随笔之——Canvas(画布)
- UI初级第四课   视图控制器——iOS学习连载18