一次对LCS的TDD过程
|
leon_a
2007-09-26
首先根据TDD原则,给出测试用例
package graph;
import junit.framework.TestCase;
/**
* @author B.Chen
*/
public class TestLCS extends TestCase {
public TestLCS(String name) {
super(name);
}
private LCS lcs;
public void setUp() throws Exception {
super.setUp();
lcs = new LCS();
}
public void tearDown() throws Exception {
super.tearDown();
lcs = null;
}
/**
* test case lcs
*/
public void testLCS() {
assertEquals("abgdfe", lcs.lcs("afsfwabgdfedfs", "fsdfwefwgfsdfsabgdfef"));
assertEquals(7, lcs.maxLength("afsfwabgdfedfs", "fsdfwefwgfsdfsabgdfedf"));
}
}
|
|
|
leon_a
2007-09-26
然后给出LCS类的能通过测试用例的空方法
package graph;
public class LCS {
public String lcs(String a, String b) {
// TODO
return "abgdfe";
}
public int maxLength(String a, String b) {
String length = lcs(a, b);
// TODO
// return length.length();
return 7;
}
}
进行测试驱动开发 开始开发过程 |
|
|
leon_a
2007-09-26
LCS算法原理:
求两个字符串最长公共子串的问题。大体解法是用一个矩阵来记录两个字符串中所有位置的两个字符之间的匹配情况,若是匹配则为1,否则为0。然后求出对角线最长的1序列,其对应的位置就是最长匹配子串的位置. 实现过程
package graph;
/**
* @author B.Chen
*/
public class LCS {
/**
* @param a
* @param b
* @return lcs string
*/
public String lcs(String a, String b) {
if (a.length() == 0 || b.length() == 0) {
return "";
}
int[][] matrix = new int[a.length() + 1][b.length() + 1];
for (int i = 0; i < a.length() + 1; i++) {
matrix[i][0] = 0;
}
for (int i = 0; i < b.length() + 1; i++) {
matrix[0][i] = 0;
}
String[] arrayA = a.split("");
String[] arrayB = b.split("");
int maxloop = 0;
int position = 0;
for (int i = 1; i < a.length() + 1; i++) {
for (int j = 1; j < b.length() + 1; j++) {
if (arrayA[i - 1].equals(arrayB[j - 1])) {
matrix[i][j] = matrix[i - 1][j - 1] + 1;
if (matrix[i][j] > maxloop) {
maxloop = matrix[i][j];
position = i;
}
} else {
matrix[i][j] = 0;
}
}
}
StringBuffer result = new StringBuffer();
if (maxloop == 0) {
return "";
}
for (int i = position - maxloop; i < position; i++) {
result.append(arrayA[i]);
}
return result.toString();
}
/**
* @param a
* @param b
* @return int lcs length
*/
public int maxLength(String a, String b) {
String length = lcs(a, b);
return length.length();
}
}
|
|
|
leon_a
2007-09-26
然后完善单元测试用例
package graph;
import junit.framework.TestCase;
/**
* @author B.Chen
*/
public class TestLCS extends TestCase {
public TestLCS(String name) {
super(name);
}
private LCS lcs;
public void setUp() throws Exception {
super.setUp();
lcs = new LCS();
}
public void tearDown() throws Exception {
super.tearDown();
lcs = null;
}
/**
* test case lcs
*/
public void testLCS() {
assertEquals("abgdfe", lcs.lcs("afsfwabgdfedfs", "fsdfwefwgfsdfsabgdfef"));
assertEquals(7, lcs.maxLength("afsfwabgdfedfs", "fsdfwefwgfsdfsabgdfedf"));
assertEquals("", lcs.lcs("abc", "def"));
assertEquals("", lcs.lcs("", "abc"));
assertEquals("", lcs.lcs("abc", ""));
assertEquals("abgd fe", lcs.lcs("afsfwabgd fedfs", "fsdfwefwgfsdfsabgd fef"));
}
}
即完成一次完整的测试驱动开发,与单元测试 |

