A gene string can be represented by an 8-character long string, with choices from "A", "C", "G", "T". Suppose we need to investigate about a mutation (mutation from "start" to "end"), where ONE mutation is defined as ONE single character changed in the gene string. For example, "AACCGGTT" -> "AACCGGTA" is 1 mutation. Also, there is a given gene "bank", which records all the valid gene mutations. A gene must be in the bank to make it a valid gene string. Now, given 3 things - start, end, bank, your task is to determine what is the minimum number of mutations needed to mutate from "start" to "end". If there is no such a mutation, return -1. Note: Starting point is assumed to be valid, so it might not be included in the bank. If multiple mutations are needed, all mutations during in the sequence must be valid. You may assume start and end string is not the same. Example 1: start: "AACCGGTT" end: "AACCGGTA" bank: ["AACCGGTA"] return: 1 Example 2: start: "AACCGGTT" end: "AAACGGTA" bank: ["AACCGGTA", "AACCGCTA", "AAACGGTA"] return: 2 Example 3: start: "AAAAACCC" end: "AACCCCCC" bank: ["AAAACCCC", "AAACCCCC", "AACCCCCC"] return: 3
the same with word ladder
写的时候语法上出了一些问题
第5行不用给char数组赋大小
第20行用stringbuilder的时候曾经写成:String afterMutation = new StringBuilder(cur).setCharAt(i, c).toString(); 这会有错因为.setCharAt()函数返回值是void;替代方法可以是char[] array = string.toCharArray(); string = new String(array);
1 public class Solution { 2 public int minMutation(String start, String end, String[] bank) { 3 if (start==null || end==null || start.length()!=end.length()) return -1; 4 int steps = 0; 5 char[] mutations = new char[]{'A', 'C', 'G', 'T'}; 6 HashSet<String> validGene = new HashSet<String>(); 7 for (String str : bank) { 8 validGene.add(str); 9 } 10 if (!validGene.contains(end)) return -1; 11 if (validGene.contains(start)) validGene.remove(start); 12 Queue<String> q = new LinkedList<String>(); 13 q.offer(start); 14 while (!q.isEmpty()) { 15 int size = q.size(); 16 for (int k=0; k<size; k++) { 17 String cur = q.poll(); 18 for (int i=0; i<cur.length(); i++) { 19 for (char c : mutations) { 20 StringBuilder ss = new StringBuilder(cur); 21 ss.setCharAt(i, c); 22 String afterMutation = ss.toString(); 23 if (afterMutation.equals(end)) return steps+1; 24 if (validGene.contains(afterMutation)) { 25 validGene.remove(afterMutation); 26 q.offer(afterMutation); 27 } 28 } 29 } 30 } 31 steps++; 32 } 33 return -1; 34 } 35 }