Interleaving String (Java)

来源:互联网 发布:癫佬正传观后感知乎 编辑:程序博客网 时间:2024/05/16 11:43

Given s1s2s3, find whether s3 is formed by the interleaving of s1 and s2.

For example,
Given:
s1 = "aabcc",
s2 = "dbbca",

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

令visited[i][j]代表取s1的前i位和s2的前j位是否可以组成s3的前i+j位。


Source

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


0 0
原创粉丝点击