Étant donné 2 chaînes, je veux trouver le premier match d'au moins quatre caractères.Java: Trouver des correspondances entre les chaînes
C'est le code que j'ai actuellement pour le faire. Cela fonctionne correctement, mais je pense qu'il pourrait y avoir une meilleure façon de le faire. Y a-t-il des inefficacités criantes ou de mauvaises pratiques dans ce que je fais? Y a-t-il des bibliothèques communes, comme Apache Commons, dont je devrais profiter, mais je ne le suis pas?
Ne vous inquiétez pas pour la classe Gene
- elle contient uniquement la chaîne en question. En outre, GeneMatch()
signifie qu'aucune correspondance n'existe, tandis que le constructeur GeneMatch
avec des arguments indique qu'une correspondance a été trouvée.
Constants.MIN_MATCH
== 4, dans ce cas.
public static GeneMatch findMatch(Gene g0, Gene g1) {
String g0DNA = g0.getDNA();
String g1DNA = g1.getDNA();
if (g0DNA.equals("") || g1DNA.equals("")) { //there won't be a match if one is empty
return new GeneMatch();
}
int g0Left = -1;
int g0Right = -1;
int g1Left = -1;
int g1Right = -1;
String window;
for (int inx = 0; inx <= g0DNA.length() - Constants.MIN_MATCH; inx++) {
window = g0DNA.substring(inx, inx + Constants.MIN_MATCH);
if (g1DNA.indexOf(window) != -1) {
g0Left = inx;
g0Right = inx + Constants.MIN_MATCH;
g1Left = g1DNA.indexOf(window);
g1Right = g1Left + Constants.MIN_MATCH;
/* grow the match to the right
* while the two right indices are less than the lengths of their respective strings, and the
* characters at the indices match, increment each index
*/
while (g0Right < g0DNA.length() && g1Right < g1DNA.length() && g0DNA.charAt(g0Right) == g1DNA.charAt(g1Right)) {
g0Right++;
g1Right++;
}
break; //we've already found a match, no need to continue sliding the window
}
}
//now that the indices are found, convert to Genes
if (g0Left == -1 || g0Right == -1 || g1Left == -1 || g1Right == -1) { //no match found
return new GeneMatch();
}
Gene gL0 = new Gene(g0DNA.substring(0, g0Left));
Gene gL1 = new Gene(g1DNA.substring(0, g1Left));
Gene g0match = new Gene(g0DNA.substring(g0Left, g0Right));
Gene g1match = new Gene(g1DNA.substring(g1Left, g1Right));
Gene gR0 = new Gene(g0DNA.substring(g0Right));
Gene gR1 = new Gene(g1DNA.substring(g1Right));
//sanity check
assert g0DNA.equals(gL0.getDNA() + g0match.getDNA() + gR0.getDNA()) : "g0 didn't add up";
assert g1DNA.equals(gL1.getDNA() + g1match.getDNA() + gR1.getDNA()) : "g1 didn't add up";
return new GeneMatch(gL0, gR0, g0match, g1match, gL1, gR1);
}
J'ai peur de savoir comment vous allez (re) l'utiliser. Etes-vous sûr de ne pas vouloir utiliser un des logiciels disponibles pour aligner deux séquences? http://en.wikipedia.org/wiki/Sequence_alignment_software – Tim