面试题 01.05. 一次编辑

public boolean oneEditAway(String first, String second) {
        int m = first.length();
        int n = second.length();
        if(Math.abs(m-n)>1) return false;
        if(m == 0 || n == 0) return true;
        if(m==n){
            //替换
            boolean b = false;
            for(int i = 0;i<m;i++){
                if(second.charAt(i) != first.charAt(i)){
                    if(!b){
                        b = true;
                    }else{
                        return false;
                    }
                }
            }
        }else if(m<n){
            //增加
            int i = 0;
            int j = 0;
            boolean b = false;
            while(i<m){
                if(first.charAt(i) != second.charAt(j)){
                    if(!b){
                        b = true;
                        j++;
                    }else{
                        return false;
                    }
                }else{
                    i++;
                    j++;
                }
            }
        }else{
            //删除
            int i = 0;
            int j = 0;
            boolean b = false;
            while(j<n){
                if(first.charAt(i) != second.charAt(j)){
                    if(!b){
                        b = true;
                        i++;
                    }else{
                        return false;
                    }
                }else{
                    i++;
                    j++;
                }
            }
        }
        return true;
    }

 

posted @ 2020-08-22 14:27  欣姐姐  阅读(132)  评论(0编辑  收藏  举报