美文网首页
LintCode交叉字符串

LintCode交叉字符串

作者: Arnold134777 | 来源:发表于2016-03-26 21:37 被阅读524次

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

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

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

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

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

public class Solution {
    /**
     * Determine whether s3 is formed by interleaving of s1 and s2.
     * @param s1, s2, s3: As description.
     * @return: true or false.
     */
    public boolean isInterleave(String s1, String s2, String s3) {
        if(null == s1 || null == s2 || null == s3 || s1.length() + s2.length() != s3.length())
            return false;
        if(s1.length() <= 0 && s2.length() <= 0 && s3.length() <= 0)
            return true;
        
        boolean[][] common = new boolean[s1.length() + 1][s2.length() + 1];
        for(int i = 1;i <= s1.length();i++)
        {
            if(s1.charAt(i - 1) == s3.charAt(i - 1))
            {
                common[i][0] = true;
            }
        }
        
        for(int i = 1;i <= s2.length();i++)
        {
            if(s2.charAt(i - 1) == s3.charAt(i - 1))
            {
                common[0][i] = true;
            }
        }
        
        for(int i = 1;i <= s1.length();i++)
        {
            for(int j = 1;j <= s2.length();j++)
            {
                if(s1.charAt(i - 1) == s3.charAt(i + j - 1))
                {
                    common[i][j] = common[i - 1][j];
                }
                
                if(common[i][j])
                {
                    continue;
                }
                
                if(s2.charAt(j - 1) == s3.charAt(i + j - 1))
                {
                    common[i][j] = common[i][j - 1];
                }
            }
        }
        return common[s1.length()][s2.length()];
    }
}

相关文章

  • LintCode交叉字符串

    给出三个字符串:s1、s2、s3,判断s3是否由s1和s2交叉构成。 样例比如 s1 = "aabcc" s2 =...

  • lintcode 交叉字符串

    给出三个字符串:s1、s2、s3,判断s3是否由s1和s2交叉构成。样例比如 s1 = "aabcc" s2 = ...

  • LintCode-交叉字符串-动态规划

    描述 给出三个字符串:s1、s2、s3,判断s3是否由s1和s2交叉构成。 样例 比如 s1 = "aabcc" ...

  • [leetcode/lintcode 题解] 解码字符串 ·

    leetcode/lintcode 题解] 解码字符串 · Decode String 【题目描述】 给出一个表...

  • python 字符串倒置(lintcode)

    描述: 字符串置换 原题地址:http://www.lintcode.com/zh-cn/problem/stri...

  • lintCode题解(8)

    标签(空格分隔): lintCode 旋转字符串 给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)...

  • TypeScript 08 - 高级类型

    交叉类型 联合类型 类型保护 可以为 null 的类型 字符串字面量类型 1. 交叉类型 交叉类型是将多个类型合并...

  • Delete Digits

    Delete Digits 今天是一道有关字符串和贪婪算法的题目,来自LintCode,难度为Medium,Acc...

  • lintcode 字符串查找

    对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 targe...

  • lintcode 旋转字符串

    给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)题目比较简单,只要注意处理一下旋转的个数大于字符串...

网友评论

      本文标题:LintCode交叉字符串

      本文链接:https://www.haomeiwen.com/subject/lkwdlttx.html