*187. Repeated DNA Sequences (hashmap, one for loop)(difference between subsequence & substring)


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.

Example:

Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"

Output: ["AAAAACCCCC", "CCCCCAAAAA"]

Solution: count the frequency of 10 letter words

class Solution {
    //find all the 10-letter-long sequences that occur more than once in a DNA molecule
    public List<String> findRepeatedDnaSequences(String s) {
        //substring -- subset n +n-1+...+1: n-k+1
        List<String> res = new ArrayList<String>();
        Map<String,Integer> map = new HashMap<String,Integer>();
        int n = s.length();
        int k  =10;
        if(n < k) return res;
        for(int i = 0; i<=n-k; i++){//11-10 1
            String sub = s.substring(i, i+k);
            if(map.containsKey(sub)){
                map.put(sub, map.get(sub)+1);
            }else {
                map.put(sub, 1);
            }
        }
        for(Map.Entry<String, Integer> entry : map.entrySet()){
            if(entry.getValue() >1){
                res.add(entry.getKey());
            }
        }
        return res;
    }
}

Solution 2: two HashSet with a non-duplicate feature.

public List<String> findRepeatedDnaSequences(String s) {
    Set seen = new HashSet(), repeated = new HashSet();
    for (int i = 0; i + 9 < s.length(); i++) {
        String ten = s.substring(i, i + 10);
        if (!seen.add(ten))//if add then first time, else add it
            repeated.add(ten);
    }
    return new ArrayList(repeated);
}

subsequence & substring

subsequence: subset 2^n

substring: continous string : n+n-1+n-2+...+1

优质内容筛选与推荐>>
1、execute immediate 执行时有into 变量的时注意ORA-00905: 缺失关键字
2、第八章 设计用户界面 之 给Web程序应用用户界面设计
3、cycling -avoid the vicious cycle
4、如果您想在页面中显示出来当前asp.net程序占用了多少内存,那么可以使用:
5、APP泄露航班信息 80元买到周杰伦鹿晗等明星航班行程


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn