首页 > 试题广场 >

字符串的交错组成

[编程题]字符串的交错组成
  • 热度指数:2120 时间限制:C/C++ 4秒,其他语言8秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定三个字符串str1、str2 和aim,如果aim包含且仅包含来自str1和str2的所有字符,而且在aim中属于str1的字符之间保持原来在str1中的顺序属于str2的字符之间保持原来在str2中的顺序,那么称aim是str1和str2的交错组成。实现一个函数,判断aim是否是str1和str2交错组成,如果是请输出“YES”,否则输出“NO”。


输入描述:
输出三行,分别表示三个字符串str1,str2和aim。 , 表示字符串长度。


输出描述:
输出“YES”或者“NO”。(不包含引号)
示例1

输入

AB
12
1AB2

输出

YES
示例2

输入

2019
9102
22001199

输出

NO

备注:
时间复杂度,空间复杂度。(n表示字符串str1长度,m表示s字符串tr2长度)
这题的后台用例应该全是出现 len(str1) + len(str2) == len(aim) && aim 的字符刚好全是来自 str1 和 str2,所以分别判断 str1 与 str2 的在 aim 中的出现顺序是否一致即可
发表于 2021-09-13 15:32:44 回复(0)
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s1 = sc.nextLine();
        String s2 = sc.nextLine();
        String s3 = sc.nextLine();
        int a = s1.length(), b = s2.length(), c = s3.length();
        if (a + b != c) {
            System.out.print("NO");
        } else if (func(s1, s2, s3)) {
            System.out.print("YES");
        } else {
            System.out.print("NO");
        }
    }
    public static boolean func(String s1, String s2, String s3) {
        boolean[][] f = new boolean[s1.length() + 1][s2.length() + 1];
        f[0][0] = true;
        for (int i = 1; i <= s1.length(); i++) {
            if (s1.charAt(i - 1) == s3.charAt(i - 1)) {
                f[i][0] = true;
            } else {
                break;
            }
        }
        for (int j = 1; j <= s2.length(); j++) {
            if (s2.charAt(j - 1) == s3.charAt(j - 1)) {
                f[0][j] = true;
            } else {
                break;
            }
        }
        for (int i = 1; i <= s1.length(); i++) {
            for (int j = 1; j <= s2.length(); j++) {
                f[i][j] = (f[i -1][j] == true && s1.charAt(i - 1) == s3.charAt(i + j - 1)) || (f[i][j -1] == true && s2.charAt(j - 1) == s3.charAt(i + j - 1));
            }
        }
        return f[s1.length()][s2.length()];
    }
}
java 100%

发表于 2020-08-24 00:21:01 回复(0)