81,092
社区成员
发帖
与我相关
我的任务
分享
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
</head>
<body>
<h3>确定两字符串的编辑距离</h3>
<form action="EditDistance" method="post">
<s:textfield name="s" label="输入字符串一" required="true"></s:textfield><br/>
<s:textfield name="t" label="输入字符串一" required="true"></s:textfield><br/>
<s:submit value="提交"></s:submit>
</form>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="linyu" extends="struts-default">
<action name="EditDistance" class="linyu.action.EditDistance">
<result>/success.jsp</result>
</action>
</package>
</struts>
package linyu.action;
import com.opensymphony.xwork2.ActionSupport;
public class EditDistance extends ActionSupport{
public String s="a";
public String t="b";
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
public String getT() {
return t;
}
public void setT(String t) {
this.t = t;
}
private static int Minimum(int a, int b, int c) {
int mi;
mi = a;
if (b < mi) {
mi = b;
}
if (c < mi) {
mi = c;
}
return mi;
}
public String excute() throws Exception{
int d[][]; // matrix
int n; // length of s
int m; // length of t
int i; // iterates through s
int j; // iterates through t
char s_i; // ith character of s
char t_j; // jth character of t
int cost; // cost
String editdistance;
// Step 1
n = s.length();
m = t.length();
if (n == 0) {
editdistance=String.valueOf(m);
}
if (m == 0) {
editdistance=String.valueOf(n);
}
d = new int[n + 1][m + 1];
// Step
for (i = 0; i <= n; i++) {
d[i][0] = i;
}
for (j = 0; j <= m; j++) {
d[0][j] = j;
}
// Step 3
for (i = 1; i <= n; i++) {
s_i = s.charAt(i - 1);
// Step 4
for (j = 1; j <= m; j++) {
t_j = t.charAt(j - 1);
// Step 5
if (s_i == t_j) {
cost = 0;
} else {
cost = 1;
}
// Step 6
d[i][j] = Minimum(d[i - 1][j] + 1, d[i][j - 1] + 1,
d[i - 1][j - 1] + cost);
}
}
// Step 7
editdistance=String.valueOf(d[n][m]);
return SUCCESS;
}
}
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
</head>
<body>
<br> 您输入的字符串是<s:property value="s"/>和<s:property value="t"/><br/>
他们的编辑距离是:<s:property value="editdistance"/>
</body>
</html>