题目:
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长字符串的长度。假设字符串只包含’a’~'z’的字符。例如,在字符串“arabacafr”中,最长的不包含重复字符的子字符串是“acfr”,长度为4。
基本思路:
首先定义函数f(i)表示以第i个字符为结尾的不包含重复字符的子字符串的最长长度。
循环判断到第i个字符时,如果第i个字符之前没出现过,那么f(i)=f(i-1)+1;如果之前出现过,记第i个字符和它上次出现的距离为d,分两种情况讨论:第一种是d小于或者等于f(i),此时第i个字符上次出现在f(i-1)对应的最长字符串中,因此f(i)=d;反之,如果d大于f(i-1),此时第i个字符上次出现在f(i-1)对应的最长字符串之前,因此f(i)=f(i-1)+1。在以下代码中,创建了一个长度为26的数组用来存储每一个字符上次出现在字符串中位置的下标。
Java实现:
import java.util.Arrays;
//48.最长不包含重复字符的字符串
public class JianZhiOffer48 {
static int longestSubstringWithoutDuplication(String str) {
int curLength=0;
int maxLength=0;
int []position=new int[26];
Arrays.fill(position,-1);
for(int i=0;i<str.length();i++) {
int prevIndex=position[str.charAt(i)-'a'];
//第i个字符没出现过,或者d>f(i-1)
if(prevIndex<0||i-prevIndex>curLength) {
++curLength;
}else {
curLength=i-prevIndex;
}
position[str.charAt(i)-'a']=i;
if(curLength>maxLength) {
maxLength=curLength;
}
}
return maxLength;
}
public static void main(String[] args){
String str="arabcacfh";
System.out.print(longestSubstringWithoutDuplication(str));
}
}