leetcode 187: Repeated DNA Sequences,leetcoderepeated

來源:互聯網
上載者:User

leetcode 187: Repeated DNA Sequences,leetcoderepeated
Total Accepted: 1161 Total Submissions: 6887

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"].

[分析]

HASHMAP方法會EXCEED  SPACE LIMIT.

因為只有4個字母,所以可以建立自己的hashkey, 每兩個BITS, 對應一個 incoming character. 超過20bit 即10個字元時, 只保留20bits.

[注意]

1. (hash<<2) + map.get(c)  符號優先順序,  << 一定要括起來.


public class Solution {    public List<String> findRepeatedDnaSequences(String s) {        List<String> res = new ArrayList<String>();        if(s==null || s.length() < 11) return res;        int hash = 0;                Map<Character, Integer> map = new HashMap<Character, Integer>();        map.put('A', 0);        map.put('C', 1);        map.put('G', 2);        map.put('T', 3);                Set<Integer> set = new HashSet<Integer>();        Set<Integer> unique = new HashSet<Integer>();                for(int i=0; i<s.length(); i++) {            char c = s.charAt(i);            if(i<9) {                hash = (hash<<2) + map.get(c);            } else {                hash = (hash<<2) + map.get(c);                hash &= (1<<20) - 1;                if( set.contains(hash) && !unique.contains(hash)) {                    res.add(s.substring(i-9, i+1));                    unique.add(hash);                } else {                    set.add(hash);                }            }        }        return res;    }}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.