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

LeetCode 97 Interleaving String

时间:2014-10-09 15:10:14      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:leetcode   java   

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()];
	}
}


LeetCode 97 Interleaving String

标签:leetcode   java   

原文地址:http://blog.csdn.net/mlweixiao/article/details/39929045

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