题解 | #重复的DNA序列#

重复的DNA序列

http://www.nowcoder.com/practice/fe9099e5308042a8af2f7aabdb3719fe

分割子串,放入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;
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务