欢迎光临
我们一直在努力

LeetCode //C - 1092. Shortest Common Supersequence

1092. Shortest Common Supersequence

Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If there are multiple valid strings, return any of them.

A string s is a subsequence of string t if deleting some number of characters from t (possibly 0) results in the string s.  

Example 1:

Input: str1 = “abac”, str2 = “cab” Output: “cabac” **Explanation: ** str1 = “abac” is a subsequence of “cabac” because we can delete the first “c”. str2 = “cab” is a subsequence of “cabac” because we can delete the last “ac”. The answer provided is the shortest such string that satisfies these properties.

Example 2:

Input: str1 = “aaaaaaaa”, str2 = “aaaaaaaa” Output: “aaaaaaaa”

Constraints:
  • 1 <= str1.length, str2.length <= 1000
  • str1 and str2 consist of lowercase English letters.

From: LeetCode Link: 1092. Shortest Common Supersequence


Solution:

Ideas:

first find the LCS. Shared LCS characters are used once; non-shared characters from both strings are inserted around them. This gives the shortest common supersequence.

Code:

char* shortestCommonSupersequence(char* str1, char* str2) {
int m = strlen(str1);
int n = strlen(str2);

int **dp = (int**)malloc((m + 1) * sizeof(int*));
for (int i = 0; i <= m; i++) {
dp[i] = (int*)calloc(n + 1, sizeof(int));
}

// LCS length DP
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (str1[i 1] == str2[j 1]) {
dp[i][j] = dp[i 1][j 1] + 1;
} else {
dp[i][j] = dp[i 1][j] > dp[i][j 1]
? dp[i 1][j]
: dp[i][j 1];
}
}
}

int maxLen = m + n;
char *ans = (char*)malloc((maxLen + 1) * sizeof(char));
int idx = maxLen;

ans[idx] = '\\0';

int i = m, j = n;

// Build answer backwards
while (i > 0 && j > 0) {
if (str1[i 1] == str2[j 1]) {
ans[idx] = str1[i 1];
i;
j;
} else if (dp[i 1][j] >= dp[i][j 1]) {
ans[idx] = str1[i 1];
i;
} else {
ans[idx] = str2[j 1];
j;
}
}

while (i > 0) {
ans[idx] = str1[i 1];
i;
}

while (j > 0) {
ans[idx] = str2[j 1];
j;
}

char *res = strdup(ans + idx);

for (int k = 0; k <= m; k++) {
free(dp[k]);
}
free(dp);
free(ans);

return res;
}

赞(0)
未经允许不得转载:171主机测评 » LeetCode //C - 1092. Shortest Common Supersequence
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址