这是我在网上碰到的一道题,挺有意思的,拿出来给大家分享。
其实这是这个网站http://www.myjavaserver.com/signup 的一道申请空间的挑战题目,如果你答对了,就可以申请5m的jsp空间,这个网站主要是针对java爱好者的,不妨试试。
后面附上我做的答案。
我的答案没有错,只不过他的网页要求返回的常量是随机产生的,大家可以把答案中的“52AUZZ”替换成网页中要求的值。
As the principal engineer of an HTTP web server, you are responsible for implementing the request processing subsystem of the server.
An incoming request for a specific resource, identified by an URI, must be dispatched to the appropriate handler according to the server configuration which maps URIs to request handlers. 'HandlerFactory.getHandler' must be implemented:
public class HandlerFactory
{
public String getHandler(String[] config, String requestUri)
{
}
}
The string array 'config' contains URI patterns and handler names. Two consecutive values form a key-value pair comprised of URI pattern and handler. 'requestUri' represents an incoming request, the URI to match against the configured handlers. 'getHandler' must return the correct handler for a given URI as a string value.
An URI pattern never contains wildcards and represents the start of an URI string, a prefix. Matching must be implemented accordingly. The handler with the longest matching URI pattern wins if more than one pattern matches. If no handler can be found, "vX0N2S0" must be returned.
Example input:
String[] config: { "/", "MainServlet", "/nav", "NavigationServlet" }
String requestUri: "/nav/test"
Correct result: "NavigationServlet"
In this example, the configuration contains a mapping of "/" to "MainServlet" and "/nav" to "NavigationServlet". In the case of an incoming URI "/nav/test.nav", "NavigationServlet" is the correct choice because its pattern is longer than that of "MainServlet".
String returnStr=null;
boolean hasEqual=false;
boolean hasStartWith=false;
int max=0;
for(int i=0;i<config.length;i=i+2)
{
if(config[i].equals(requestUri) )
{
if(max<config[i].length())
{
max = config[i].length();
returnStr = config[i + 1];
hasEqual=true;
}
}
else if(requestUri.startsWith(config[i]))
{
if(hasEqual)
{
continue;
}
else
{
hasStartWith=true;
for(int j=0;j<=config[i].length();j++)
{
String s=config[i].substring(0,j);
if(requestUri.startsWith(s))
{
if(max<j)
{
max=j;
returnStr=config[i+1];
}
}
}
}
}
else
{
if(hasEqual || hasStartWith)
{
continue;
}
else
{
for(int j=0;j<=config[i].length();j++)
{
String s=config[i].substring(0,j);
if(requestUri.startsWith(s))
{
if(max<j)
{
max=j;
returnStr=config[i+1];
}
}
}
}
}
}
if(!hasEqual &&!hasStartWith && max<2)
return "52AUZZ";
return returnStr;