Java solution, easy to understand


  • 0
    T

    Not that efficient. Main idea is to calculate the distance between Strings.

    public class Solution {
        public int minMutation(String start, String end, String[] bank) {
            if (bank.length < 1) return -1;
            int length = bank.length;
            int[] dis = new int[length];
            boolean flag = false;
            int res = 0;
            for (int i = 0; i < length; i ++) {
                dis[i] = distance(start, bank[i]);
            }
            for (int i = 0; i < length; i ++) {
                int k = distance(end, bank[i]);
                if (k == 0) {
                    flag = true;
                    res = i;
                }
            }
            res = dis[res];
            Arrays.sort(dis);
            if (!flag) return -1;
            for (int i = 0; i < length - 1; i ++) {
                if (dis[i + 1] <= res && (dis[i + 1] - dis[i] != 1 && dis[i + 1] - dis[i] != 0)) return -1;
            }
            return res;
        }
        
        private int distance(String s1, String s2) {
            int res = 0;
            for (int i = 0; i < s1.length(); i ++) {
                if (s1.charAt(i) != s2.charAt(i))
                res ++;
            }
            return res;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.