187. Repeated DNA Sequences

Medium

逻辑简单没什么好说的,维持两个hashSet, 一个装见到过的,一个装要求的重复的。遍历的时候,记得index不要越界,找到那些seen里面见过的加到repeated里,不然就加到seen里。最后hashSet转arrayList的方法很方便
List res = new ArrayList(repeated);

class Solution {
    public List findRepeatedDnaSequences(String s) {
        Set seen = new HashSet<>();
        Set repeated = new HashSet<>();
        for (int i = 0; i + 9 < s.length(); i++){
            String str = s.substring(i, i + 10);
            if (!seen.contains(str)){
                seen.add(str);
            } else {
                repeated.add(str);
            }
        }
        List res = new ArrayList(repeated);
        return res;
    }
}

你可能感兴趣的:(187. Repeated DNA Sequences)