题目链接

https://leetcode.cn/problems/one-away-lcci/

代码

class Solution {
    public boolean oneEditAway(String first, String second) {
        if(first.equals(second)){        //完全相同 0次
            return true;
        }
        int f=first.length();//短的
        int s=second.length();//长的
        //长度 差1
        if(Math.abs(f-s)>1){
            return false;
        }
        if(f>s){
            String tmp=first;
            first=second;
            second=tmp;
        }
        f=first.length();
        s=second.length();
		//处理空串
        if(first.equals("")){
            if(s==1){
                return true;
            }
            return false;
        }

        //2.一样长,修改一位
        /*
        HashSet<Character> set=new HashSet<>();
        for(char c:second.toCharArray()){
            set.add(c);
        }
        */
        int count=0;
        if(f==s){
            for(int i=0;i<f;i++){
                if(first.charAt(i)!=second.charAt(i)){
                    count++;
                }
            }
            if(count>1){
                return false;
            }
            else{
                return true;
            }
        }
        
        //1.a短b长。b的多余字符可能在头部、中间、尾部,要注意数组越界问题。
        else{
            int i=0,j=0;
            while(i<f&&j<s&&first.charAt(i)==second.charAt(j)){
                count++;
                i++;
                j++;
            }
            if(i==f&&j==s-1){
                return true;
            }
            while(i<f&&j<s&&first.charAt(i)!=second.charAt(j)){
                j++;
            }
            if(i>=f||j>=s){
                return false;
            }
            while(i<f&&j<s&&first.charAt(i)==second.charAt(j)){
                count++;
                i++;
                j++;
            }
            if(count!=f){
                return false;
            }
            return true;
        }
    }
}