Exercism————Protein Translation

题目:

Exercism————Protein Translation_第1张图片

最优解法:

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<>();

	//@Constructor
	public 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 multikeys
	void multiPut(String value,String ... keys) {
     
		for(String key : keys) {
     
			proteinMap.put(key,value);
		}
	}

	// translate the RNAChain
	List<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中

你可能感兴趣的:(Exercism,java)