187. Repeated DNA Sequences
题目链接:
这道题要求所有重复出现的序列,那么可以想到得用hash table,因为这里限制了是10个字符长的序列,所以每次其实是去掉第一个letter,再加一个letter,这个思想和rabin karp挺像的,需要用int或者long来表示string。
public class Solution { public ListfindRepeatedDnaSequences(String s) { Set res = new HashSet(); Set dup = new HashSet(); Map map = new HashMap(); map.put('A', 0); map.put('C', 1); map.put('G', 2); map.put('T', 3); int hash = 0; for(int i = 0; i < s.length(); i++) { hash = (hash << 2) | map.get(s.charAt(i)); hash &= 0xfffff; if(i >= 9 && !dup.add(hash)) { res.add(s.substring(i-9, i+1)); } } return new ArrayList(res); }}