gold-1-5


字符串有三种编辑操作:插入一个英文字符、删除一个英文字符或者替换一个英文字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。

示例 1:

输入: 
first = "pale"
second = "ple"
输出: True

示例 2:

输入: 
first = "pales"
second = "pal"
输出: False

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public boolean oneEditAway(String first, String second) {
        if (first == null && second == null) {
            return true;
        }
        if (first == null || second == null) {
            return false;
        }

        if (first.length() - second.length() > 1 || second.length() - first.length() > 1) {
            return false;
        }

        String longStr = null;
        String shortStr = null;

        if (first.length() < second.length()) {
            longStr = second;
            shortStr = first;
        } else {
            longStr = first;
            shortStr = second;
        }

        if (longStr.length() == shortStr.length()) {
            int mismatchNum = 0;

            for (int i = 0; i < longStr.length(); i++) {
                if (longStr.charAt(i) != shortStr.charAt(i)) {
                    mismatchNum++;
                }

                if (mismatchNum > 1) {
                    return false;
                }
            }
        } else {
            int longIndex = 0;
            int shortIndex = 0;
            int mismatchNum = 0;

            while (longIndex < longStr.length() && shortIndex < shortStr.length()) {
                if (longStr.charAt(longIndex) != shortStr.charAt(shortIndex)) {
                    mismatchNum++;
                    longIndex++;

                    if (mismatchNum > 1) {
                        return false;
                    }
                } else {
                    longIndex++;
                    shortIndex++;
                }
            }
        }

        return true;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !