LeetCode:Minimum ASCII Delete Sum for Two Strings
来源:互联网 发布:2015家电市场销售数据 编辑:程序博客网 时间:2024/06/05 11:27
题目链接:https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/description/
题目介绍:给出2个字符串,找出删除掉ASCII码值和最小的字符使得2个字符串相同。
解题思路:设需要编辑的2个字符串为s1[1...m]和s2[1...n],用S(i,j)表示s1[1...i]和s2[1...j]的删除字符的最小ASCII码值之和。
S(0,0)=0;
当i=0时,S(i,j)=s2[j]+S(i,j-1);
当j=0时,S(i,j)=s1[i]+S(i-1,j);
当i>0且j>0时,S(i,j)=min{s1[i]+S(i-1,j), s2[j]+S(i,j-1), cost(i,j)+S(i-1,j-1)}
其中,当s1[i]=s2[j]时,cost(i,j)=0;否则cost(i,j)=s1[i]+s2[j]。
代码如下:
class Solution {public: int minimumDeleteSum(string s1, string s2) { int size1 = s1.size(), size2 = s2.size(); if (size1 == 0 && size2 == 0) { return 0; } else if (size1 == 0) { int sum = 0; for (int i = 0; i < size2; i++) { sum += s2[i]; } return sum; } else if (size2 == 0) { int sum = 0; for (int i = 0; i < size1; i++) { sum += s1[i]; } return sum; } else { int** S = new int*[size1+1]; for (int i = 0; i < size1+1; i++) { S[i] = new int[size2+1]; } S[0][0] = 0; for (int i = 1; i < size1 + 1; i++) { S[i][0] = S[i-1][0] + s1[i-1]; } for (int i = 1; i < size2 + 1; i++) { S[0][i] = S[0][i-1] + s2[i-1]; } for (int i = 1; i < size1 + 1; i++) { for (int j = 1; j < size2 + 1; j++) { int d1 = s1[i-1] + S[i - 1][j]; int d2 = s2[j-1] + S[i][j - 1]; int d0 = S[i - 1][j - 1]; if (s1[i-1] != s2[j-1]) d0 += s1[i-1] + s2[j-1]; S[i][j] = min(d0, d1, d2); } } return S[size1][size2]; }}int min(int a, int b, int c) { int min = (a < b) ? a : b; return (min < c) ? min : c;}};
阅读全文