- 论坛徽章:
- 0
|
这是我前两天面试的一个题,本来是 C 的题,我在这里写成 JAVA 的了。
自我感觉效率还是挺高的。
/**
* 写一个函数, 查找两个字符串其中拥有的一个最长的子串。
*
* @author zy
*/
public class mostLengthSubstring
{
public String execute(String s1, String s2)
{
char[] c = this.execute(s1.toCharArray(), s2.toCharArray());
if (c != null)
return new String(c);
else
return null;
}
public char[] execute(char[] a, char[] b)
{
int aStartPos = 0;
int mostLength = 0;
for (int i = 0; i a.length - mostLength; i++)
{
for (int j = 0; j a.length - mostLength; j++)
{
if (a == b[j])
{
int pos = 1;
while ((i + pos) a.length && (j + pos) b.length)
{
if (a[i + pos] == b[j + pos])
pos++;
else
break;
}
if (pos > mostLength)
{
mostLength = pos;
aStartPos = i;
}
}
}
}
if (mostLength > 0)
{
char[] t = new char[mostLength];
for (int i = 0; i mostLength; i++)
{
t = a[aStartPos + i];
}
return t;
}
else
return null;
}
/**
* @param args
*/
public static void main(String[] args)
{
System.out.print(new mostLengthSubstring().execute("341234614614532190578910389104901", "543120-764730593413212345609-70-41098509-47109-6180"));
}
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/10921/showart_489565.html |
|