码迷,mamicode.com
首页 > 其他好文 > 详细

97. 交错字符串

时间:2020-07-18 22:15:59      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:str   图片   bsp   dfs   array   ring   public   div   har   

技术图片

 

 方法一: 动态规划

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;
    }
}

 

97. 交错字符串

标签:str   图片   bsp   dfs   array   ring   public   div   har   

原文地址:https://www.cnblogs.com/yonezu/p/13337433.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!