【72】编辑距离问题

给你两个单词 word1 和 word2,请你计算出将 word1 转换成 word2 所使用的最少操作数 。

你可以对一个单词进行如下三种操作:

插入一个字符
删除一个字符
替换一个字符
 

示例 1:

输入:word1 = "horse", word2 = "ros"
输出:3
解释:
horse -> rorse (将 'h' 替换为 'r')
rorse -> rose (删除 'r')
rose -> ros (删除 'e')
示例 2:

输入:word1 = "intention", word2 = "execution"
输出:5
解释:
intention -> inention (删除 't')
inention -> enention (将 'i' 替换为 'e')
enention -> exention (将 'n' 替换为 'x')
exention -> exection (将 'n' 替换为 'c')
exection -> execution (插入 'u')

https://leetcode-cn.com/problems/edit-distance/solution/bian-ji-ju-chi-by-leetcode-solution/ 

 思考:假设存在字符串A 和 字符串B,A的前i个字符到B的前j个字符的编辑距离表示为d[i][j]

则存在d[i][j] = min(d[i-1][j]+1,d[i][j-1]+1,d[i-1][j-1]+1) A[i]!=B[j]

或d[i][j] = min(d[i-1][j]+1,d[i][j-1]+1,d[i-1][j-1]) A[i]==B[j]

重点理解,从d[i-1][j] 推导的d[i][j]的过程,因为d[i-1][j]代表了A的前i-1个字符到B前j的编辑距离,则Ai 到 Bj,相当于在Bj后再增加一个字符与A[i]对应。也就是d[i-1][j]+1

d[i-1][j]同理分析。d[i-1][j-1],在修改Ai,使其和 Bj相同。

class Solution(object):
    def minDistance(self, word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: int
        """
        #d[i][j] 字符串A前i 到字符串B前j个的编辑距离
        #d[i][j] = min(d[i-1][j]+1,d[i][j-1]+1,d[i-1][j-1]+1)
        m = len(word1)+1
        n = len(word2)+1
        d = []
        for i in range(m):
            d.append([0]*n)
        for i in range(1,n):
            d[0][i] = i
        for i in range(1,m):
            d[i][0] = i
        
        for i in range(1,m):
            for j in range(1,n):
                if word1[i-1]==word2[j-1]:
                    d[i][j] = min(min(d[i-1][j]+1,d[i][j-1]+1),d[i-1][j-1]) 
                else:
                    d[i][j] = min(min(d[i-1][j]+1,d[i][j-1]+1),d[i-1][j-1]+1)
        return d[m-1][n-1] 

 

 

AI实战-仿真交易欺诈行为分类数据集分析预测实例(含10个源代码+419.69 KB完整的数据集) 代码手工整理,无语法错误,可运行。 包括:10个代码,共49.42 KB;数据大小:1个文件共419.69 KB。 使用到的模块: pandas os sklearn.model_selection.train_test_split sklearn.ensemble.RandomForestClassifier sklearn.metrics.classification_report imblearn.over_sampling.SMOTE sklearn.linear_model.LogisticRegression sklearn.metrics.accuracy_score datetime.datetime sklearn.svm.SVC seaborn sklearn.preprocessing.StandardScaler sklearn.preprocessing.OrdinalEncoder sklearn.compose.ColumnTransformer imblearn.pipeline.Pipeline numpy matplotlib.pyplot statsmodels.formula.api sklearn.model_selection.StratifiedKFold sklearn.metrics.roc_auc_score contextlib pickle sklearn.pipeline.Pipeline sklearn.preprocessing.OneHotEncoder sklearn.preprocessing.PowerTransformer torch torch.nn torch.nn.BCELoss torch.optim.Adam warnings scipy.stats.normaltest scipy.stats.chi2_contingency wolta.data_tools.col_types wolta.data_tools.seek_null wolta.data_tools.unique_amounts wolta.feature_tools.list_deletings wolta.data_tools.make_numerics wolta.data_tools.stat_sum wolta.data_tools.corr_analyse collections.Counter wolta.model_tools.compare_models wolta.model_tools.get_best_model sklearn.metrics.confusion_matrix sklearn.metrics.ConfusionMatrixDisplay sklearn.ensemble.GradientBoostingClassifier xgboost sklearn.model_selection.GridSearchCV sklearn.preprocessing.LabelEncoder sklearn.ensemble.StackingClassifier sklearn.metrics.roc_curve plotly.express wordcloud.WordCloud wordcloud.STOPWORDS
AI实战-阿尔茨海默氏病患者的健康信息数据集分析预测实例(含17个源代码+591.06 KB完整的数据集) 代码手工整理,无语法错误,可运行。 包括:17个代码,共143.32 KB;数据大小:1个文件共591.06 KB。 使用到的模块: numpy pandas os seaborn matplotlib.pyplot sklearn.model_selection.train_test_split sklearn.ensemble.RandomForestClassifier sklearn.metrics.accuracy_score sklearn.metrics.confusion_matrix sklearn.metrics.classification_report sklearn.preprocessing.LabelEncoder sklearn.preprocessing.StandardScaler warnings sklearn.svm.SVC mealpy.GA mealpy.Problem sklearn.neural_network.MLPClassifier mealpy.BinaryVar sklearn.exceptions.ConvergenceWarning IPython.display.clear_output sklearn.utils.resample sklearn.compose.ColumnTransformer sklearn.pipeline.Pipeline sklearn.preprocessing.PowerTransformer sklearn.decomposition.PCA sklearn.linear_model.LogisticRegression sklearn.metrics.precision_score sklearn.metrics.recall_score sklearn.metrics.f1_score sklearn.preprocessing.MinMaxScaler sklearn.metrics.ConfusionMatrixDisplay sklearn.model_selection.RepeatedKFold sklearn.model_selection.cross_val_score sklearn.model_selection.RandomizedSearchCV xgboost.XGBClassifier tensorflow pickle plotly.express plotly.subplots.make_subplots plotly.graph_objects sklearn.model_selection.GridSearchCV sklearn.model_selection.cross_validate sklearn.tree.DecisionTreeClassifier yellowbrick.classifier.ClassPredictionError yellowbrick.classifier.ROCAUC yellowbrick.classifier.ConfusionMatrix sklearn.ensemble.GradientBoostingClassifier lightgbm.LGBMClassifier catboost.CatBoostClassifier imblearn.under_sampling.RandomUnderSampler imblearn.over_sampling.RandomOverSampler sklearn.metrics.matthews_corrcoef optuna torch torch.nn torch.optim imblearn.pipeline.Pipeline imblearn.over_sampling.SMOTE sklearn.ensemble.AdaBoostClassifier sklearn.neighbors.KNeighborsClassifier sklearn.discriminant_analysis.LinearDiscriminantAnalysis sklearn.pipeline.make_pipeline collections.Counter sklearn.preprocessing.OneHotEncoder sklearn.model_selection.cross_val_predict sklearn.metrics.precision_recall_curve sklearn
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值