当前位置: 首页 > 工具软件 > Strings edit > 使用案例 >

Google面试题:M-One Edit Distance

段干麒
2023-12-01

http://www.jiuzhang.com/article/Google2016Experience%20%E8%BD%AF%E4%BB%B6%E5%B7%A5%E7%A8%8B%E5%B8%88onsite/

http://www.lintcode.com/zh-cn/problem/edit-distance-ii/


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

样例

Given s = "aDb", t = "adb"
return true

题目意思:判断第二个字符串是否能由第一个字符串转换一次得到,转换方式有:插入一个、删除一个、替换一个


public class Solution {
    /**
     * @param s a string
     * @param t a string
     * @return true if they are both one edit distance apart or false
     */
    public boolean isOneEditDistance(String s, String t) {
        if(s==null || t==null) return false;
        
        int n1 = s.length();
        int n2 = t.length();
        
        if(Math.abs(n1-n2)>1)
            return false;
        
        for(int i=0; i<Math.min(n1,n2); i++){
            if(s.charAt(i)!=t.charAt(i)){
                if(n1>n2)
                    return s.substring(i+1,s.length()).equals(t.substring(i,t.length()));
                else if(n1<n2)
                    return s.substring(i,s.length()).equals(t.substring(i+1,t.length()));
                else
                    return s.substring(i+1,s.length()).equals(t.substring(i+1,t.length()));
            }
        }
        
        return Math.abs(n1-n2)==1;
    }
}



 类似资料: