public boolean diff(String word1, String word2) {
        // return true iff the two words only diff in one character
        int diff = 0;
        for (int i = 0; i < word1.length(); ++i) {
            if (word1.charAt(i) != word2.charAt(i)) {
                ++diff;
            }
            if (diff > 1)
                return false;
        }
        return true;
    }