如何找到给定字符串的最长重复子字符串

编程入门 行业动态 更新时间:2024-10-27 02:30:06
本文介绍了如何找到给定字符串的最长重复子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是新的java并且我被赋予了分配以找到字符串的最长子字符串。 我在网上研究,看来解决这个问题的好方法是实现后缀树。 如果您有任何其他解决方案,请告诉我如何做到这一点。请记住,这是假设用低水平的java知识完成的。

I am new java and I was given assignment to find the longest substring of a string. I research online and seems that good way of approaching this problem will be implementing suffix tree. Please let me know how I can do this or if you have any other solutions. keep in mind this is suppose to be done with low level of java knowledge.

谢谢你。

P.S。测试仪字符串让人放心。

P.S. the tester string is reassuring.

/** This method will find the longest substring of a given string. String given here is reassuring. */ public String longestRepeatedSubstring() { String longestRepeatedSubstring = ""; for (int i = 0; i<text.length(); i++ ) { String one = text.substring(0,i); for(int o = 0; o<text.length();o++) { Sting two = text.substring(0,o); if(one.equals(two)) { longestRepeatedSubstring = one; } } } return longestRepeatedSubstring; }

推荐答案

如果您调试代码,会看到你的代码没有按你的想法行事。 AFAIK你需要至少三个循环,你不能假设你只会从第一个角色开始。这是一种可能的解决方案。

If you debug your code you will see that you the code isn't doing what you think. AFAIK you need at least three loops and you can't assume you would only start from the first character. Here is one possible solution.

public static void main(String[] args) throws IOException { String longest = longestDuplicate("ababcaabcabcaab"); System.out.println(longest); } public static String longestDuplicate(String text) { String longest = ""; for (int i = 0; i < text.length() - 2 * longest.length() * 2; i++) { OUTER: for (int j = longest.length() + 1; j * 2 < text.length() - i; j++) { String find = text.substring(i, i + j); for (int k = i + j; k <= text.length() - j; k++) { if (text.substring(k, k + j).equals(find)) { longest = find; continue OUTER; } } break; } } return longest; }

打印

abcaab

安慰打印 r 不是 s 这是我的第一次猜测。 ;)

for "reassuring" it prints r not s which was my first guess. ;)

更多推荐

如何找到给定字符串的最长重复子字符串

本文发布于:2023-11-30 01:05:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648200.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   最长

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!