题解 | #重复的DNA序列#
重复的DNA序列
http://www.nowcoder.com/practice/fe9099e5308042a8af2f7aabdb3719fe
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param DNA string字符串 1
* @return string字符串一维数组
*/
public String[] repeatedDNA (String DNA) {
// write code here
HashMap<String, Integer> hashMap = new HashMap<>();
ArrayList<String> arrayList = new ArrayList<>();
int len = DNA.length();
for (int i = 0; i <= len - 10; i++) {
String tmpStr = DNA.substring(i, i + 10);
if (!isValid(tmpStr)) {
continue;
}
else {
int num = hashMap.getOrDefault(tmpStr, 0);
num++;
hashMap.put(tmpStr, num);
}
}
// 此时,HashMap 存放了所有的合法子串出现的次数
// 我们再重新遍历一次,将出现 2 次的子串添加到结果集中去
for (int i = 0; i <= len - 10; i++) {
String tmpStr = DNA.substring(i, i + 10);
int num = hashMap.getOrDefault(tmpStr, 0);
if (num > 1 && (!arrayList.contains(tmpStr))) {
arrayList.add(tmpStr);
}
}
String[] res = new String[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
res[i] = arrayList.get(i);
}
return res;
}
public boolean isValid(String str) {
boolean bool = true;
for (int i = 0; i < str.length(); i++) {
if (!(str.charAt(i) == 'A' || str.charAt(i) == 'C' || str.charAt(i) == 'G' || str.charAt(i) == 'T')) {
bool = false;
break;
}
}
return bool;
}
}