分割子串,放入set.如果set中已经存在该子串,那么加入返回列表。再遍历set,找到最先出现的串即可。

public class Solution {
    Set<String> set =new LinkedHashSet<>();
    public String[] repeatedDNA (String DNA) {
        List<String> list = new LinkedList<>();
        while(DNA.length()>=10){
            if(check(DNA.substring(0,10))){
                if(set.contains(DNA.substring(0,10))){
                    if(!list.contains(DNA.substring(0,10)))
                        list.add(DNA.substring(0,10));
                }
                else set.add(DNA.substring(0,10));
            }
            DNA = DNA.substring(1);
        }
        String[] res = new String[list.size()];
        int index = 0;
        for(String s:set){
            if(list.contains(s))res[index++]=s;
        }
        return res;
    }
    public boolean check(String s){
        for(int i=0;i<s.length();++i){
            if(s.charAt(i)=='A'||s.charAt(i)=='C'||s.charAt(i)=='T'||s.charAt(i)=='G')continue;
            else return false;
        }
        return true;
    }
}