Idea: Brute force. Without loss of generality, let us assume S is not shorter than T. Now there are three cases:
1) s.length()-t.length()>1, must be over one edit distance, false;
2) s.length()==t.length(), if s and t have different characters at exactly one position, return true; otherwise return false;
3) s.length()-t.length()==1, remove a character from s, then s should equal t; otherwise return false.
Only case 3) needs some tricks. The character should be removed is the first character not matched. After removing, the other characters should be exactly the same.
Time: O(n) Space: O(n) (I used a string builder to cache the string after removing a character in case 3). Space can be reduced to O(1) by modifying and shifting characters directly in the string. But I think it does not worth the time required to handle string shift in Java).
Code:
public class Solution {
public boolean isOneEditDistance(String s, String t) {
if(s.length()<t.length())
return isOneEditDistance(t,s);
if(s.length()-t.length()>1)
return false;
if(s.length()==t.length())
{
int counter=0;
for(int i=0;i<s.length()&&counter<2;i++)
{
if(s.charAt(i)!=t.charAt(i))
counter++;
}
return counter==1;
}
int i;
for(i=0;i<t.length();i++)
{
if(s.charAt(i)!=t.charAt(i))
break;
}
StringBuilder builder=new StringBuilder(s);
builder.deleteCharAt(i);
return t.equals(builder.toString());
}
}
O(1) space Code:
public class Solution {
public boolean isOneEditDistance(String s, String t) {
if(s.length()<t.length())
return isOneEditDistance(t,s);
if(s.length()-t.length()>1)
return false;
int counter=0;
if(s.length()==t.length())
{
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)!=t.charAt(i))
counter++;
}
return counter==1;
}
int j=0;
while(j<t.length())
{
if(s.charAt(j)!=t.charAt(j))
break;
j++;
}
while(j<t.length())
{
if(s.charAt(j+1)!=t.charAt(j))
break;
j++;
}
return j==t.length();
}
}
No comments:
Post a Comment