欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

(每日一练c语言)交错字符串

时间:2023-04-25
交错字符串

 

给定三个字符串 s1、s2、s3,请你帮忙验证 s3 是否是由 s1 和 s2 交错 组成的。

两个字符串 s 和 t 交错 的定义与过程如下,其中每个字符串都会被分割成若干 非空 子字符串:

s = s1 + s2 + ..、+ snt = t1 + t2 + ..、+ tm|n - m| <= 1交错 是 s1 + t1 + s2 + t2 + s3 + t3 + ... 或者 t1 + s1 + t2 + s2 + t3 + s3 + ...

提示:a + b 意味着字符串 a 和 b 连接。

示例 1:

输入:s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"输出:true

示例 2:

输入:s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"输出:false

示例 3:

输入:s1 = "", s2 = "", s3 = ""输出:true

提示:

0 <= s1.length, s2.length <= 1000 <= s3.length <= 200s1、s2、和 s3 都由小写英文字母组成

以下程序实现了这一功能:

#include #include #include #include static bool isInterleave(char *s1, char *s2, char *s3){int i, j;int len1 = strlen(s1);int len2 = strlen(s2);int len3 = strlen(s3);if (len1 + len2 != len3){return false;}bool *table = malloc((len1 + 1) * (len2 + 1) * sizeof(bool));bool **dp = malloc((len1 + 1) * sizeof(bool *));for (i = 0; i < len1 + 1; i++){dp[i] = &table[i * (len2 + 1)];}dp[0][0] = true;for (i = 1; i < len1 + 1; i++){dp[i][0] = dp[i - 1][0] && s1[i - 1] == s3[i - 1];}for (i = 1; i < len2 + 1; i++){dp[0][i] = dp[0][i - 1] && s2[i - 1] == s3[i - 1];}for (i = 1; i < len1 + 1; i++){for (j = 1; j < len2 + 1; j++){bool up = dp[i - 1][j] && s1[i - 1] == s3[i + j - 1];bool left = dp[i][j - 1] && s2[j - 1] == s3[i + j - 1];dp[i][j] = up || left;}}return dp[len1][len2];}int main(int argc, char **argv){if (argc != 4){fprintf(stderr, "Usage: ./test s1 s2 s3n");exit(-1);}printf("%sn", isInterleave(argv[1], argv[2], argv[3]) ? "true" : "false");return 0;}

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。