Java solution


  • 0
    J

    no use of substring as it takes time to construct substring.

        public boolean isOneEditDistance(String s, String t) {
            if (s.length() == t.length()) {
                int cnt = 0;
                for (int i = 0; i < s.length(); i++) {
                    if (s.charAt(i) != t.charAt(i)) cnt++;
                    if (cnt >= 2) return false;
                }
                return cnt == 1;
            } else {
                String longer, shorter;
                if (s.length() > t.length()) {
                    longer = s;
                    shorter = t;
                } else {
                    longer = t;
                    shorter = s;
                }
                int i = 0;
                for (int j = 0; i < shorter.length(); ) {
                    if (j >= longer.length()) return false;
                    if (longer.charAt(j) != shorter.charAt(i)) j++;
                    else { 
                        i++;
                        j++;
                    }
                    if (j - i > 1) return false;
                }
                return (longer.length() - i == 1);
            }
        }
    

Log in to reply
 

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