欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Exercism————Protein Translation

程序员文章站 2022-04-19 17:17:35
...

题目:

Exercism————Protein Translation

最优解法:

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