Interleaving String

来源:互联网 发布:c语言求100以内的素数 编辑:程序博客网 时间:2024/04/28 07:17

Fair Interleaving StringMy Submissions

54%
Accepted

Given three strings: s1, s2, s3, 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.

Challenge Expand 
Tags Expand 

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 == null || s2 == null || s3 == null            || s3.length() != s1.length() + s2.length()) {                return false;        }         boolean[][] dp = new boolean[s1.length() + 1][s2.length() + 1];        dp[0][0] = true;        for (int i = 1; i < dp.length; i++) {            if (s3.charAt(i - 1) == s1.charAt(i - 1)) {                <span style="color:#ff6666;">dp[i][0] = dp[i - 1][0];</span>            }        }        for (int j = 1; j < dp[0].length; j++) {            if (s3.charAt(j - 1) == s2.charAt(j - 1)) {                <span style="color:#ff6666;">dp[0][j] = dp[0][j - 1];</span>            }        }        for (int i = 1; i < dp.length; i++) {            for (int j = 1; j < dp[0].length; j++) {                char temp = s3.charAt(i + j - 1);               <span style="color:#ff0000;"> if (temp == s1.charAt(i - 1) && temp == s2.charAt(j - 1)) {                    dp[i][j] = (dp[i - 1][j] || dp[i][j - 1]);                } else if (temp == s1.charAt(i - 1)) {                    dp[i][j] = dp[i - 1][j];                } else if (temp == s2.charAt(j - 1)) {                    dp[i][j] = dp[i][j - 1];                }</span>            }        }        return dp[s1.length()][s2.length()];    }}


0 0
原创粉丝点击