Here is the code in Java: public class distanceOfStrings { public static void main(String args[]){ String s1 ="abcd"; String s2 ="abcde"; char[] as1 = s1.toCharArray(); char[] as2 = s2.toCharArray(); int s1Len = s1.length(); int s2Len = s2.length(); int j=0; int diff = 0; if ( s1Len-s2Len > 1 || s2Len-s1Len > 1 ){ System.out.println("Two strings are not at a distance of 1"); return; } if (s1Len != s2Len ) { for (int i=0; i<s1Len && j<s2Len;) { if (as1[i] == as2[j]) { i++; j++; } else if (diff == 0 && s1Len > s2Len ) { diff = 1; i++; } else if (diff == 0 && s1Len < s2Len) { diff = 1; j++; } else { diff = 2; System.out.println("Two strings are not at a distance of 1"); return; } } } else { for (int i=0; i<s1Len && j<s2Len;) { if (as1[i] == as2[j]) { i++; j++; } else if (diff == 0) { diff = 1; i++;j++; } else { diff = 2; System.out.println("Two strings are not at a distance of 1"); return; } } } System.out.println("Yep..Two strings are at a distance of 1"); } } --------------------------------
On Sun, Jun 20, 2010 at 4:10 PM, sharad <sharad20073...@gmail.com> wrote: > Write a code which will find whether two strings are at a distance of > 1. Distance of 1 meaning that they differ by the insertion/deletion or > replacement of 1 char. For e.g. > s1 -> abcd > s2->acd > > s1-> abcd > s2-> ascd > > s1->abcd > s2->abcde > > -- > You received this message because you are subscribed to the Google Groups > "Algorithm Geeks" group. > To post to this group, send email to algoge...@googlegroups.com. > To unsubscribe from this group, send email to > algogeeks+unsubscr...@googlegroups.com<algogeeks%2bunsubscr...@googlegroups.com> > . > For more options, visit this group at > http://groups.google.com/group/algogeeks?hl=en. > > -- cheers Jeeva -- You received this message because you are subscribed to the Google Groups "Algorithm Geeks" group. To post to this group, send email to algoge...@googlegroups.com. To unsubscribe from this group, send email to algogeeks+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/algogeeks?hl=en.