码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode-One Edit Distance

时间:2014-12-15 06:31:20      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   on   div   art   

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 }

 

Leetcode-One Edit Distance

标签:style   blog   io   ar   color   sp   on   div   art   

原文地址:http://www.cnblogs.com/lishiblog/p/4164065.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!