CC--Q1.5

1.5 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
pale, pIe -> true
pales. pale -> true
pale. bale -> true
pale. bake -> false

public class Solution {
    public static boolean canReplaceOneChar(String s, String t) {
        int count = 0, len_s = s.length(), len_t = t.length();
        for (int i = 0, j = 0; i < len_s && j < len_t; i++, j++) {
            if (s.charAt(i) != t.charAt(j))    
                count++;
        }
        if (count != 1)
            return false;
        else
            return true;   
    }

    public static boolean canDeleteOneChar(String s, String t) {
        int len_s = s.length(), len_t = t.length();
        for (int i = 0, j = 0; i < len_s && j < len_t; i++, j++) {
            if (s.charAt(i) != t.charAt(j)) {
                return s.substring(i + 1).equals(t.substring(j));
            }
        }
        return true;
    }

    public static boolean isOneEditDistance(String s, String t) {
        if (s.equals(t))
            return false;
        int len_s = s.length(), len_t = t.length();
        if (Math.abs(len_s - len_t) > 1)
            return false;
        if (len_s - len_t == 1) {
            return canDeleteOneChar(s, t);
        }
        if (len_t - len_s == 1) {
            return canDeleteOneChar(t, s);
        }
        if (len_s == len_t) {
            return canReplaceOneChar(s, t);
        }
    
        return true;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容