题目:
最优解法:
package practice;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
class ProteinTranslator
{
static final String STOP = "STOP";HashMap<String,String> proteinMap = new HashMap<>();//@Constructorpublic ProteinTranslator() {
multiPut("Methionine", "AUG");multiPut("Phenylalanine", "UUU", "UUC");multiPut("Leucine", "UUA", "UUG");multiPut("Serine", "UCU", "UCC", "UCA", "UCG");multiPut("Tyrosine", "UAU", "UAC");multiPut("Cysteine", "UGU", "UGC");multiPut("Tryptophan","UGG");multiPut(STOP, "UAA", "UAG", "UGA");}// Set one value to multikeysvoid multiPut(String value,String ... keys) {
for(String key : keys) {
proteinMap.put(key,value);}}// translate the RNAChainList<String> translate(String RNAChain) throws IllegalArgumentException{
ArrayList<String> proteins = new ArrayList<>();String codon,protein;for(int i = 0;i < RNAChain.length()/3;i += 3) {
codon = RNAChain.substring(i,i+3);protein = proteinMap.get(codon);if(codon == STOP) {
break;}if(protein == null) {
throw new IllegalArgumentException("The condon must be condon");}proteins.add(protein);}return proteins;}}
解析:
利用HaspMap多对一的关系,将codon和protein放进HashMap中,**“multput”**方法是本解法的亮点,再利用for翻译,最后将结果放进ArrayList中