Leetcode-One Edit Distance

Given two strings S and T, determine if they are both one edit distance apart.

Analysis:

Must be exactly one distance apart. Not the same.

Solution:

 1 public class Solution {
 2     public boolean isOneEditDistance(String s, String t) {
 3         if (s.length()==0 && t.length()==0) return false;
 4         if (s.length()+t.length()==1) return true;
 5         
 6         if (Math.abs(s.length()-t.length())>1) return false;        
 7 
 8         if (s.length()==t.length()) return isOneReplace(s,t);
 9 
10         if (s.length()>t.length()) return isOneInsert(s,t);
11         else return isOneInsert(t,s);
12         
13     }
14 
15     public boolean isOneInsert(String a, String b){
16         //a is 1 char longer than b, we determine whether a and b is one insertion distance.
17 
18         boolean modified = false;
19 
20         int index1 = 0;
21         int index2 = 0;
22 
23         while (index2<b.length()){
24             if (a.charAt(index1)==b.charAt(index2)){
25                 index1++;
26                 index2++;
27             } else {
28                 if (modified) return false;
29                 else {
30                     index1++;
31                     modified = true;
32                 }
33             }
34         }
35         return true;
36     }
37 
38 
39     public boolean isOneReplace(String a, String b){
40         //a and b have the same length, we determine whether they are one replace aparted.
41         boolean modified = false;
42         int index1=0;
43         while (index1<a.length())
44             if (a.charAt(index1)==b.charAt(index1))
45                 index1++;
46             else if (modified) return false;
47             else {
48                 index1++;
49                 modified = true;
50             }
51         if (modified) return true;
52         else return false;
53     }
54               
55  
56         
57     
58 }

 

posted @ 2014-12-15 05:25  LiBlog  阅读(373)  评论(0编辑  收藏  举报