博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JAVA算法:最长重复子串问题(JAVA解题)
阅读量:4039 次
发布时间:2019-05-24

本文共 1806 字,大约阅读时间需要 6 分钟。

JAVA算法:最长重复子串问题(JAVA解题)

Given a string str, find the longest repeating non-overlapping substring in it. In other words find 2 identical substrings of maximum length which do not overlap. If there exists more than one such substring return any of them.

Examples:

Input : str = "geeksforgeeks"

Output : geeks

Input : str = "aab"

Output : a

Input : str = "aabaabaaba"

Output : aaba

Input : str = "aaaaaaaaaaa"

Output : aaaaa

Input : str = "banana"

Output : an 
         or na


算法设计

package com.bean.algorithm.basic;public class LongestRepeatingSubstring {	// Returns the longest repeating non-overlapping	// substring in str	static String longestRepeatedSubstring(String str) {		int n = str.length();		int LCSRe[][] = new int[n + 1][n + 1];		String res = ""; // To store result		int res_length = 0; // To store length of result		// building table in bottom-up manner		int i, index = 0;		for (i = 1; i <= n; i++) {			for (int j = i + 1; j <= n; j++) {				// (j-i) > LCSRe[i-1][j-1] to remove				// overlapping				if (str.charAt(i - 1) == str.charAt(j - 1) && LCSRe[i - 1][j - 1] < (j - i)) {					LCSRe[i][j] = LCSRe[i - 1][j - 1] + 1;					// updating maximum length of the					// substring and updating the finishing					// index of the suffix					if (LCSRe[i][j] > res_length) {						res_length = LCSRe[i][j];						index = Math.max(i, index);					}				} else {					LCSRe[i][j] = 0;				}			}		}		// If we have non-empty result, then insert all		// characters from first character to last		// character of String		if (res_length > 0) {			for (i = index - res_length + 1; i <= index; i++) {				res += str.charAt(i - 1);			}		}		return res;	}	// Driver program to test the above function	public static void main(String[] args) {		String str = "aabaabaaba";		System.out.println(longestRepeatedSubstring(str));	}}

程序运行结果:

 aaba

 

 

转载地址:http://nntdi.baihongyu.com/

你可能感兴趣的文章
Android中电池信息(Battery information)的取得
查看>>
SVN客户端命令详解
查看>>
Android/Linux 内存监视
查看>>
Linux系统信息查看
查看>>
用find命令查找最近修改过的文件
查看>>
Android2.1消息应用(Messaging)源码学习笔记
查看>>
Android之TelephonyManager类的方法详解
查看>>
android raw读取超过1M文件的方法
查看>>
ubuntu下SVN服务器安装配置
查看>>
MPMoviePlayerViewController和MPMoviePlayerController的使用
查看>>
CocoaPods实践之制作篇
查看>>
[Mac]Mac 操作系统 常见技巧
查看>>
苹果Swift编程语言入门教程【中文版】
查看>>
捕鱼忍者(ninja fishing)之游戏指南+游戏攻略+游戏体验
查看>>
iphone开发基础之objective-c学习
查看>>
iphone开发之SDK研究(待续)
查看>>
计算机网络复习要点
查看>>
Variable property attributes or Modifiers in iOS
查看>>
NSNotificationCenter 用法总结
查看>>
C primer plus 基础总结(一)
查看>>