当前位置:网站首页>[daily training] interview question 01.05 One edit

[daily training] interview question 01.05 One edit

2022-05-14 13:57:41Puppet__

subject

There are three editing operations for Strings : Insert a character 、 Delete or replace a character . Given two strings , Write a function to determine if they only need to be done once ( Or zero times ) edit .

Example 1:
Input :
first = “pale”
second = “ple”
Output : True

Example 2:
Input :
first = “pales”
second = “pal”
Output : False

Code

package dayLeetCode;

public class dayleetcode0105 {
    
    public boolean oneEditAway(String first, String second) {
    
        boolean flag = true;
        // len The value of can only be -1 0 1
        int len = second.length() - first.length();
        if (len > 1 || len < -1){
    
            return false;
        }

        int i = 0, j = 0;
        //  Record the number of edits 
        int cnt = 0;
        while (i < first.length() && j < second.length()){
    
            if (first.charAt(i) != second.charAt(j)){
    
                //  Inserted 、 Delete 、 Or replace operation 
                //  Insert 
                if (len == 1){
    
                    cnt++;
                    //  First reduce and then add guarantee i unchanged 
                    i--;
                }else if(len == 0){
    
                    //  Replace 
                    cnt++;
                } else if (len == -1){
    
                    //  Delete 
                    cnt++;
                    j--;
                }
            }
            if (cnt > 1){
    
                flag = false;
                break;
            }
            i++;
            j++;
        }
        return flag;
    }

    public static void main(String[] args) {
    
        dayleetcode0105 obj = new dayleetcode0105();
        System.out.println(obj.oneEditAway("pale", "ple"));
    }
}


原网站

版权声明
本文为[Puppet__]所创,转载请带上原文链接,感谢
https://chowdera.com/2022/134/202205141350563463.html

随机推荐