Share my accepted Java solution!


  • 2
    I
    public class Solution {
        public int ladderLength(String start, String end, Set<String> dict) {
            if (start.equals(end)) {
                return 1;
            }
            int level = 2;
            int count = 1;
            int length = start.length();
            int previous = 0;
            ArrayList<String> array = new ArrayList<String>();
            array.add(start);
            while (array.size() > 0) {
                String current = array.remove(0);
                if (distanceBetweenString(current, end) == 1) {
                    return level;
                }
                for (int i = 0; i < length; ++i) {
                    for (char c = 'a'; c < 'z'; ++c) {
                        String s = current.substring(0, i) + c + current.substring(i + 1, length);
                        if (dict.contains(s)) {
                            array.add(s);
                            dict.remove(s);
                            previous++;
                        }
                    }
                }
                count--;
                if (count == 0) {
                    level++;
                    count = previous;
                    previous = 0;
                }
            }
            return 0;
        }
        
        public int distanceBetweenString(String s1, String s2) {
            int difference = 0;
            int length = s1.length();
            for (int i = 0; i < length; ++i) {
                if (s1.charAt(i) != s2.charAt(i)) {
                    difference++;
                }
            }
            return difference;
        }
    }

Log in to reply
 

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