剑指Offer48:最长不含重复字符的子字符串

题目:

请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度

假设字符串中只包含'a'~'z'的字符

例如,在字符串“arabcacfr”中,最长的不含重复字符的子字符串是“acfr”,长度为4

思路:

我们从头遍历,考虑每次所读的当前字符为结尾的字符串的不含重复字符的最长子字符串问题。

如我们读到了第i个字符,假设当前以i为结尾的字符串的最长不含重复字符的字符串长为x,下一个字符i+1,会有两种情况:

1)i+1字符第一次出现,则以i+1为结尾的最长字符串长度直接为x+1;

2)i+1字符出现过,分为:

a、在i+1上一次出现的位置,在最长子字符串中,则此i+1字符不能添加在子字符串后。

b、在i+1上一次出现的位置,不在最长子字符串中,则i+1字符可添加,长度x+1。

代码:

//动态规划
public class Main {
	public static void main(String[] args) {
		String s = "arabcacfr";
		System.out.println(getLenStr(s));	
	}
	
	public static String getLenStr(String s) {
		// max用于保存位置和长度
		int maxloc = 0;
		int maxlength = 1;
		// len用于保存此字符之前字符的最长字符串长度
		int len = maxlength;
		// 用长度为26的数组来保存字符上次出现的位置
		int[] arr = new int[26];
		// 循环 
		// 计算以每一个位置为结尾的最长字符串长度
		for(int i=1;ilen) {
					len = len +1;
				}else {
					len = dis;
				}
			}
			
			// 更新此字符串的出现位置
			arr[s.charAt(i)-'a'] = i;
			if(maxlength < len) {
				maxloc = i;
				maxlength = len;
			}
		}
		return s.substring(maxloc-maxlength+1,maxloc+1);
	}
}

 

你可能感兴趣的:(算法)