*LeetCode-Interleaving String

来源:互联网 发布:php 房源管理系统 编辑:程序博客网 时间:2024/06/07 12:32

2d 动归 boolean matrix 每一位看左边或者上面 上面的话t [ i - 1 ] [ j ] == true && s2.charAt ( j ) == s3.charAt( i + j )就说明 t[ i ] [ j ] = true 同理左边假如符合也可以

但是要注意初始化 要多出来一行一列代表一边假如是空string的情况 然后这样的实际代码里面 index实际就不是从0开始的了 记得减一

public class Solution {    public boolean isInterleave(String s1, String s2, String s3) {        int m = s1.length();        int n = s2.length();        int len = s3.length();        if ( m + n != len )            return false;        boolean [][] table = new boolean [ m + 1 ][ n + 1 ];        for ( int i = 0; i <= m; i ++ ){            for ( int j = 0; j <= n; j ++ ){                if ( i == 0 && j == 0 )                    table[ i ][ j ] = true;                else if ( i == 0 )                    table[ i ][ j ] = ( table[ i ][ j - 1 ] && s2.charAt( j - 1 ) == s3.charAt( i + j - 1 ));                else if ( j == 0 )                    table[ i ][ j ] = ( table[ i - 1 ][ j ] && s1.charAt( i - 1 ) == s3.charAt( i + j - 1 ));                else                    table[ i ][ j ] = (( table[ i ][ j - 1 ] && s2.charAt( j - 1 ) == s3.charAt( i + j - 1 )) || ( table[ i - 1 ][ j ] && s1.charAt( i - 1 ) == s3.charAt( i + j - 1 )));            }        }        return table[ m ][ n ];    }}


0 0
原创粉丝点击