• LeetCode Interleaving String


    Given three strings: s1s2s3, determine whether s3 is formed by the interleaving of s1 and s2.

    Example

    For s1 = "aabcc", s2 = "dbbca"

    • When s3 = "aadbbcbcac", return true.
    • When s3 = "aadbbbaccc", return false

    解题思路:简历辅助空间dp[s1.lenght()+1][s2.length()+1],dp[i][j]代表的是s[0...i-1]和s2[0..j-1]能否交错组成s3[i+j-1]

    dp[i][j]的取值决策:

    1、s[i-1]= s3[i+j-1],那么dp[i][j] 的值由s1[i-2]和s2[j-1]是否交错组成s3[i+j-2],也就是dp[i-1][j]是否为true;

    2、s2[j-1] = s3[i+j-1],那么dp[i][j] 的值由s1[i-1]和s2[j-2]是否交错组成s3[i+j-2],也就是dp[i-1][j]是否为true

    根据以上情况dp[i][j]=s1[i - 1] == s3[i + j - 1] && dp[i - 1][j] ||s2[j - 1] == s3[i + j - 1] && dp[i][j - 1],否则为false;

    package cn.edu.algorithm.huawei;
    
    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 (s1.length() + s2.length() != s3.length())
                return false;
            if (s1 == null || s1.length() == 0)
                return s2.equals(s3);
            if (s2 == null || s2.length() == 0)
                return s1.equals(s3);
    
            boolean[][] dp = new boolean[s1.length() + 1][s2.length() + 1];
            char[] arr1 = s1.toCharArray();
            char[] arr2 = s2.toCharArray();
            char[] arr3 = s3.toCharArray();
    
            dp[0][0] = true;
            for (int i = 1; i <= s1.length(); i++) {
                if (arr1[i - 1] != arr3[i - 1]) {
                    break;
                }
                dp[i][0] = true;
            }
    
            for (int j = 1; j <= s2.length(); j++) {
                if (arr2[j - 1] != arr3[j - 1]) {
                    break;
                }
                dp[0][j] = true;
            }
    
            for (int i = 1; i <= s1.length(); i++) {
                for (int j = 1; j <= s2.length(); j++) {
                    if (arr1[i - 1] == arr3[i + j - 1] && dp[i - 1][j] || arr2[j - 1] == arr3[i + j - 1] && dp[i][j - 1]) {
                        dp[i][j] = true;
                    }
                }
            }
            return dp[s1.length()][s2.length()];
        }
    
        public static void main(String[] args) {
            String s1 = "abbcddef";
            String s2 = "accbbbcd";
            String s3 = "abbcddefaccbbbcd";
            Solution s = new Solution();
            System.out.println(s.isInterleave(s1, s2, s3));
        }
    }

    该代码还可以进行空间压缩

  • 相关阅读:
    Android使用SharedPreferences
    Flex程序基本结构顺序结构程序设计
    FLEX程序设计函数
    FLEX程序设计XML(2)
    FLEX程序设计事件和事件机制鼠标事件
    FLEX字符串
    FLEX程序基本结构循环结构程序设计
    Enum 作为一个数据源绑定(收藏)
    FLEX程序设计数字处理
    flex程序设计面向对象基础
  • 原文地址:https://www.cnblogs.com/googlemeoften/p/5837996.html
Copyright © 2020-2023  润新知