当输出或比较的结果在原数据结构中是连续排列的时候,可以使用滑动窗口算法求解。
最大相同子串
题目描述:获取两个字符串中最大相同子串。
举例:
String str1 = “abcwerthello1yuiodefabcdef”;
String str2 = “cvhello1bnabcdefm”;输出:[hello1, abcdef]
思路:
滑动窗口的应用之一。
1.因题目未说明字符串长度大小关系,故需要手动判断两个字符串孰长孰短,以选择出长度较短的字符串进行操作;
2.因匹配结果可能包含多个子串,故建立列表存储成功匹配的子串;
3.因题目要求”最大相同子串“,故外层循环用以控制当前匹配子串的长度i,即滑动窗口大小i,由大至小变化;
4.内层循环利用两个临时变量构造大小为i的滑动窗口,并且由左至右开始滑动匹配,将匹配到的结果存储到列表中。
5.结束当前内层循环后,判断列表是否为空:如果为空,则减小窗口大小,进行下一次滑动;如果不为空,说明当前长度匹配成功,返回结果。
实现代码如下:
public class MatchLongEst {
public static void main(String[] args) {
String str1 = "abcwerthello1yuiodefabcdef";
String str2 = "cvhello1bnabcdefm";
List<String> result = getMaxSameString(str1, str2);
System.out.println(result);
}
public static List<String> getMaxSameString(String s1, String s2) {
if (s1 == null || s1.length() == 0 || s2 == null || s2.length(