題目連接:https://leetcode.com/problems...code
這道題要求全部重複出現的序列,那麼能夠想到得用hash table,由於這裏限制了是10個字符長的序列,因此每次實際上是去掉第一個letter,再加一個letter,這個思想和rabin karp挺像的,須要用int或者long來表示string。leetcode
public class Solution { public List<String> findRepeatedDnaSequences(String s) { Set<String> res = new HashSet(); Set<Integer> dup = new HashSet(); Map<Character, Integer> 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); } }