免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1182 | 回复: 0
打印 上一主题 下一主题

[JAVA] 查找两个字符串共有的一个最长的子串 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-03-05 02:12 |只看该作者 |倒序浏览

这是我前两天面试的一个题,本来是 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
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP