zoukankan      html  css  js  c++  java
  • 97. 交错字符串

     方法一: 动态规划

    class Solution {
        public boolean isInterleave(String s1, String s2, String s3) {
            int n1 = s1.length(), n2 = s2.length(), n3 = s3.length();
            if(n1 + n2 != n3) return false;
            char[] arr1 = s1.toCharArray(), arr2 = s2.toCharArray(), arr3 = s3.toCharArray();
            boolean[][] dp = new boolean[n1+1][n2+1];
            dp[0][0] = true;
            for(int i = 1; i <= n1; i++) {
                if(dp[i-1][0] && arr1[i-1] == arr3[i-1]) dp[i][0] = true;
            }
            for(int i = 1; i <= n2; i++) {
                if(dp[0][i-1] && arr2[i-1] == arr3[i-1]) dp[0][i] = true;
            }
            for(int i = 1; i <= n1; i++) {
                for(int j = 1; j <= n2; j++) {
                    if(arr1[i-1] == arr3[i+j-1]) {
                        dp[i][j] = dp[i-1][j];
                    }
                    if(arr2[j-1] == arr3[i+j-1]) {
                        dp[i][j] = dp[i][j] || dp[i][j-1];
                    }
                }
            }
            return dp[n1][n2];
        }
    }

     方法二:记忆化回溯

    class Solution {
        char[] arr1;
        char[] arr2;
        char[] arr3;
        public boolean isInterleave(String s1, String s2, String s3) {
            int n1 = s1.length(), n2 = s2.length(), n3 = s3.length();
            if(n1 + n2 != n3) return false;
            visited = new boolean[n1+1][n2+1];
            arr1 = s1.toCharArray();
            arr2 = s2.toCharArray();
            arr3 = s3.toCharArray();
            return dfs(0,0,0);
        }
        boolean[][] visited;
        public boolean dfs(int i, int j, int k) {
            if(k == arr3.length) return true;
            if(visited[i][j]) return false;
            else if(i < arr1.length && arr1[i] == arr3[k] && dfs(i+1,j,k+1)) return true;
            else if(j < arr2.length && arr2[j] == arr3[k] && dfs(i,j+1,k+1)) return true;
            visited[i][j] = true;
            return false;
        }
    }
  • 相关阅读:
    C#_WinForm接收命令行参数
    SQLite不支持的SQL语法总结
    Thirft框架介绍
    jquery获取复选框的值
    REST构架风格介绍:状态表述转移
    RESTful HTTP的实践infoQ
    C#如何在webBrowser1控件通过TagName,Name查找元素(没有ID时)遍历窗体元素
    Html TO Ubb and Ubb TO Html
    SQL 位运算
    Memcached真的过时了吗?【转帖】
  • 原文地址:https://www.cnblogs.com/yonezu/p/13337433.html
Copyright © 2011-2022 走看看