• 【LintCode】29 交叉字符串


    29. 交叉字符串

    一、原题

    描述

    给出三个字符串:s1、s2、s3,判断s3是否由s1和s2交叉构成。

    您在真实的面试中是否遇到过这个题? 是

    样例

    比如 s1 = "aabcc" s2 = "dbbca"

    ​ - 当 s3 = "aadbbcbcac",返回 true.

    ​ - 当 s3 = "aadbbbaccc", 返回 false.

    挑战

    要求时间复杂度为O(n^2)或者更好

    二、解法

    2.1 解法一, 动态规划

    创建一个(n+1)×(m+1)的dp数组, dp[i][j]记录长度为i的str1 与 长度为j的str2的字符串能否构成长度为(i+j)的str3;

    public class Solution {
        /**
         * @param s1: A string
         * @param s2: A string
         * @param s3: A string
         * @return: Determine whether s3 is formed by interleaving of s1 and s2
         */
        public boolean isInterleave(String s1, String s2, String s3) {
            // write your code here
            if(s1 == null || s2 == null || s3 == null || s1.length() + s2.length() != s3.length()){
                return false;     
            }
            
            int n = s1.length(), m = s2.length(), nm = s3.length();
            boolean[][] dp = new boolean[n + 1][m + 1];
            dp[0][0] = true;
            // 初始化第一列, 此时str2为空串
            for(int i = 1; i <= n; i++){
                if(s1.charAt(i-1) == s3.charAt(i - 1)){
                    dp[i][0] = dp[i-1][0];
                }
            }
            // 初始化第一行, 此时str1为空串
            for(int i = 1; i <= m; i++){
                if(s2.charAt(i-1) == s3.charAt(i-1)){
                    dp[0][i] = dp[0][i-1];
                }
            }
            
            for(int i = 1; i <= n; i++){
                for(int j = 1; j <= m; j++){
                    if(s1.charAt(i-1) == s3.charAt(i+j - 1)){
                        dp[i][j] = dp[i-1][j];
                    }
                    if(dp[i][j]){
                        continue;
                    }
                    if(s2.charAt(j-1) == s3.charAt(i+j-1)){
                        dp[i][j] = dp[i][j-1];
                    }
                }
                
            }
            return dp[n][m];
        }
    }
    

    2.2 解法二, 回溯法

    暂时不会,插个眼, 日后补充;

  • 相关阅读:
    常见的单链表题目
    一个string类的几个函数
    strcpy和memcpy的区别
    字符串及 strcpy几种写法
    什么函数不能声明为虚函数
    STL中Vector和List的底层数据结构
    C/C++堆、栈及静态数据区详解
    tcp四次握手
    几个知识点
    内存对齐的规则与作用
  • 原文地址:https://www.cnblogs.com/jxkun/p/9427392.html
Copyright © 2020-2023  润新知