leetcode 面试题 01.05. 一次编辑【字符串】

首先,为了便于运算,可以先将first字符串通过处理后始终保持为更长的一个字符串,然后对于len1与len2相等和不相等两种情况进行处理。
相等的情况比较简单,只能进行一次替换操作,只要两个字符串不相等的字符数大于1个,那么返回false;
不相等的情况,由于经过处理后,second字符串较短,使用两个指针分别遍历两个字符串,当找到不相等的字符时,令j–,即模拟在second插入一个字符,并对插入字符的数量进行统计,大于一个即返回false。

class Solution {
    public boolean oneEditAway(String first, String second) {
        int len1 = Math.max(first.length(), second.length());
        int len2 = Math.min(first.length(), second.length());
        if (len1 - len2 > 1)
            return false;
        //first为长字符串,second为短字符串
        if (len1 != first.length()){
            String tmp = first;
            first = second;
            second = tmp;
        }
        if(len1 - len2>1)return false;
        int count=1;
        if(len1!=len2){
        //长度不相等
            for(int i=0,j=0; i<len1 && j<len2;i++,j++){
                if(first.charAt(i) != second.charAt(j)){
                //字符不相等,在较短的字符串中插入一个字符,即j--
                    j--;
                    count--;
                    if(count<0)return false;
                }
            }
        }else{
        //长度相等,统计不同的字符的数量
            for(int i=0; i<len1;i++){
                if(first.charAt(i) != second.charAt(i)){
                    count--;
                    if(count<0)return false;
                }                
            }
        }
        return true;
    }
}
发布了35 篇原创文章 · 获赞 0 · 访问量 299

猜你喜欢

转载自blog.csdn.net/er_ving/article/details/104916159