161. One Edit Distance

Problem

Given two strings S and T, determine if they are both one edit distance apart.

Solution

只有一个编辑距离,那就是只能在增,删,减中的一步
Bug : 两个字符串相等时应该返回 false

class Solution {
    
    bool helper( const string& s, int s_begin, const string& t, int t_begin){
        while(s_begin < s.size()){
            if(s[s_begin++] != t[t_begin++]) return false;
        }
        return true;
    }
public:
    bool isOneEditDistance(string s, string t) {
    
        const int s_len = s.size(), t_len = t.size();
        if( s_len < t_len ) return isOneEditDistance( t, s);
        if( s_len - t_len >= 2) return false;
        
        for( int i = 0; i < s_len ; i++){
            if(s[i] != t[i]) {
                int s_begin = i + 1, t_begin = ( s_len == t_len ? i + 1 : i );
                
                return helper(s, s_begin, t, t_begin);
            }
        }
        return false;
    }
};



Sure, here's the implementation of the `feline_fixes` function in Python: ```python def feline_fixes(start, goal): m, n = len(start), len(goal) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(m + 1): dp[i][0] = i for j in range(n + 1): dp[0][j] = j for i in range(1, m + 1): for j in range(1, n + 1): if start[i - 1] == goal[j - 1]: dp[i][j] = dp[i - 1][j - 1] else: dp[i][j] = 1 + min(dp[i - 1][j - 1], dp[i][j - 1], dp[i - 1][j]) return dp[m][n] ``` This function uses dynamic programming to solve the problem. The `dp` matrix is initialized with 0s, and the first row and column are filled with the distances between the empty string and the prefixes of the start and goal words. Then, the matrix is filled in row-major order using the following recurrence: - If the i-th character of start is equal to the j-th character of goal, then the distance between the prefixes of length i and j is the same as the distance between the prefixes of length i-1 and j-1. - Otherwise, we can transform the prefix of start into the prefix of goal using one of three operations: substitution (if we replace the i-th character of start with the j-th character of goal), deletion (if we delete the i-th character of start), or insertion (if we insert the j-th character of goal after the i-th character of start). We take the minimum of the costs of these three operations plus 1 (to account for the current mismatch) to get the distance between the prefixes of length i and j. Finally, the function returns the value in the bottom-right corner of the matrix, which represents the distance between the entire start and goal words.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值