|
| 1 | +package com.ctci.arraysandstrings; |
| 2 | + |
| 3 | +/** |
| 4 | + * @author rampatra |
| 5 | + * @since 24/11/2018 |
| 6 | + */ |
| 7 | +public class OneAway { |
| 8 | + |
| 9 | + /** |
| 10 | + * Checks if two strings are only one edit away, that is, by inserting, deleting, or editing |
| 11 | + * at max one character in {@code s1} it becomes same as {@code s2}. |
| 12 | + * |
| 13 | + * @param s1 |
| 14 | + * @param s2 |
| 15 | + * @return |
| 16 | + */ |
| 17 | + private static boolean isOneEditAway(String s1, String s2) { |
| 18 | + if (s1.length() == s2.length()) { |
| 19 | + return isOneCharacterDiffAtMax(s1, s2); |
| 20 | + } else if (s1.length() < s2.length()) { |
| 21 | + return checkForMaxOneInsertOrDeleteInS1(s1, s2); |
| 22 | + } else { |
| 23 | + return checkForMaxOneInsertOrDeleteInS1(s1, s2); |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + private static boolean isOneCharacterDiffAtMax(String s1, String s2) { |
| 28 | + boolean foundDiff = false; |
| 29 | + for (int i = 0; i < s1.length(); i++) { |
| 30 | + if (s1.charAt(i) != s2.charAt(i)) { |
| 31 | + if (foundDiff) { |
| 32 | + return false; // means we already found a difference earlier |
| 33 | + } |
| 34 | + foundDiff = true; |
| 35 | + } |
| 36 | + } |
| 37 | + return true; |
| 38 | + } |
| 39 | + |
| 40 | + private static boolean checkForMaxOneInsertOrDeleteInS1(String s1, String s2) { |
| 41 | + int i = 0; |
| 42 | + int j = 0; |
| 43 | + int s1Len = s1.length(); |
| 44 | + int s2Len = s2.length(); |
| 45 | + while (i < s1Len && j < s2Len) { |
| 46 | + if (s1.charAt(i) != s2.charAt(j)) { |
| 47 | + if (s1Len > s2Len) { |
| 48 | + i++; |
| 49 | + } else { |
| 50 | + j++; |
| 51 | + } |
| 52 | + continue; |
| 53 | + } |
| 54 | + i++; |
| 55 | + j++; |
| 56 | + } |
| 57 | + return Math.abs(i - j) <= 1; // check whether difference in two strings is not more than 1 |
| 58 | + } |
| 59 | + |
| 60 | + public static void main(String[] args) { |
| 61 | + System.out.println("pale, ple: " + isOneEditAway("pale", "ple")); |
| 62 | + System.out.println("pales,pale: " + isOneEditAway("pales", "pale")); |
| 63 | + System.out.println("pale, bale: " + isOneEditAway("pale", "bale")); |
| 64 | + System.out.println("pale, bake: " + isOneEditAway("pale", "bake")); |
| 65 | + System.out.println("ram, rama: " + isOneEditAway("ram", "rama")); |
| 66 | + } |
| 67 | +} |
0 commit comments