LeetCode 97 Interleaving String

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.

思路1:采用回溯法,结果超时,当s1[i]=s2[j]=s3[i+j-1]时,我们则采用栈来存贮i和j,当 1[i]与s3[i+j-1]不相等或者1s2[j]与s3[i+j-1]不相等时,则退栈。超时代码如下:
public class Solution {
	public boolean isInterleave(String s1, String s2, String s3) {
		if (s3.length() != s2.length() + s1.length())
			return false;
		int i = 0, j = 0, k = 0;
		LinkedList<Integer> l1 = new LinkedList<Integer>();
		LinkedList<Integer> l3 = new LinkedList<Integer>();
		while (k < s3.length()) {
			if (i < s1.length() && j < s2.length()) {
				if (s3.charAt(k) == s1.charAt(i)
						&& s3.charAt(k) == s2.charAt(j)) {
					l1.push(i);
					l3.push(k);
					i++;
					k++;
				} else if (s3.charAt(k) == s1.charAt(i)) {
					i++;
					k++;
				} else if (s3.charAt(k) == s2.charAt(j)) {
					j++;
					k++;
				} else {
					if (!l3.isEmpty()) {
						i = l1.poll();
						k = l3.poll();
						j=k-i+1;
						k++;
					} else {
						return false;
					}
				}
			} else if (i < s1.length()) {
				if (s3.endsWith(s1.substring(i))) {
					return true;
				} else {
					if (!l3.isEmpty()) {
						i = l1.poll();
						k = l3.poll();
						j=k-i+1;
						k++;
					} else {
						return false;
					}
				}
			} else if (j < s2.length()) {
				if (s3.endsWith(s2.substring(j))) {
					return true;
				} else {
					if (!l3.isEmpty()) {
						i = l1.poll();
						k = l3.poll();
						j=k-i+1;
						k++;
					} else {
						return false;
					}
				}
			}
		}
		return true;
	}
}

思路2,采用备忘录方法。
public class Solution {
	public boolean isInterleave(String s1, String s2, String s3) {
		if (s3.length() != s1.length() + s2.length())
			return false;
		int i, j;
		boolean[][] flag = new boolean[s1.length() + 1][s2.length() + 1];
		flag[0][0] = true;

		for (i = 1; i <= s1.length(); i++) {
			if (s3.startsWith(s1.substring(0, i)))
				flag[i][0] = true;
			else
				break;
		}

		for (i = 1; i <= s2.length(); i++) {
			if (s3.startsWith(s2.substring(0, i)))
				flag[0][i] = true;
			else
				break;
		}

		for (i = 1; i <= s1.length(); i++) {
			for (j = 1; j <= s2.length(); j++) {
				if (flag[i][j - 1] && s2.charAt(j - 1) == s3.charAt(j + i - 1))
					flag[i][j] = true;
				else if (flag[i - 1][j]&& s1.charAt(i - 1) == s3.charAt(j + i - 1))
					flag[i][j] = true;
			}
		}

		return flag[s1.length()][s2.length()];
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值