One Away : There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away.
EXAMPLE
1
2
3
4
pale , ple -> true
pales , pale -> true
pale , bale -> true
pale , bake -> false
分析
两个字符串a和b,看a距离b是否one edit away。
先看字符数的差异:
insert:b比a多一个字符,如果多了大于一个字符,那么就不是one edit away
remove:b比a少一个字符,如果少了大于一个字符,那么就无法one edit away
replace:b和a的字符数一样多
总结下来就是a和b的字符数的差异必须<=1,只有这样才有可能one edit away
再看字符内容的差异:如果要能够one edit away,那么a和b的字符的大部分都是一样的,且存在的差异最多只能有一处。
解法1
先看字符数差异是否具有one edit away的条件。如果不具备直接返回false。
如果两个字符数一样,那么用两个指针遍历a、b,当发现有两处不同时,返回false。
如果a和b差一个字符,也同时遍历a、b,发现不同时将较长字符串的指针进位,继续比较,发现两处不同是,返回false。因为insert和remove实际上是一样的,所以只看insert就行了。
比如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Round 1 :
v
ples
pales
^
Round 2 , diffCount ++ :
v
ples
pales
^
Round 3 :
v
ples
pales
^
Round 4 :
v
ples
pales
^
Round 5 :
v
ples
pales
^
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public boolean isOneAway ( String a , String b ) {
int countDiff = abs ( a . length - b . length );
if ( countDiff > 1 ) {
return false ;
}
if ( countDiff == 0 ) {
return isOneReplaceAway ( a , b );
}
if ( a . length < b . length ) {
return isOneInsertAway ( a , b );
}
return isOneInsertAway ( b , a );
}
public boolean isOneReplaceAway ( String a , String b ) {
int diffCount = 0 ;
for ( int i = 0 ; i < a . length ; i ++ ) {
if ( a . charAt ( i ) != b . charAt ( i )) {
diffCount ++ ;
}
if ( diffCount > 1 ) {
return false ;
}
}
return true ;
}
public boolean isOneInsertAway ( String a , String b ) {
int diffCount = 0 ;
int i = 0 ;
int j = 0 ;
while ( i < a . length ) {
if ( a . charAt ( i ) != b . charAt ( j )) {
diffCount ++ ;
j ++ ;
} else {
i ++ ;
j ++ ;
}
if ( diffCount > 1 ) {
return false ;
}
}
return true ;
}
评论