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

/*
* 题目:最长不含重复字符的子字符串
* 解法:动态规划
* 定义函数f(i)表示以第i个字符结尾的包含当前字符的不含重复字符的子字符串的最长长度
* 如果当前的第i个字符没有出现过,那么f(i)=f(i-1)+1,如果已经出现过,设当前元素与上次出现的距离为d,如果d小于等于
* f(i-1),说明上次出现的字符出现在f(i-1)对应的最长字符串之中,f(i)=d;如果d大于f(i-1),则f(i)=f(i-1)+1
* */
 1     public static int longestSubstringWithoutDuplication(String str){
 2         int curLength=1;
 3         int maxLength=0;
 4         // 创建一个长度为26的数组保存每个字符上次出现时在字符串中的下标
 5         int[] position=new int[26];
 6         for(int i=0;i<26;i++){
 7             position[i]=-1;
 8         }
 9         //保存第0个字符出现时在字符串中的下标
10         position[str.charAt(0)-'a']=0;
11         int len=str.length();
12         for (int i=1;i<len;i++){
13             if (position[str.charAt(i)-'a']!=-1){
14                 //说明此字符已经出现过
15                 int d=i-position[str.charAt(i)-'a'];
16                 if (d>curLength){
17                     curLength=curLength+1;
18                 }else {
19                     curLength=d;
20                 }
21                 position[str.charAt(i)-'a']=i;
22             }else {
23                 //没有有出现过
24                 curLength=curLength+1;
25                 position[str.charAt(i)-'a']=i;
26             }
27             if (curLength>maxLength) maxLength=curLength;
28         }
29         return maxLength;
30     }

 

posted @ 2018-02-11 17:59  大熊好好写代码  阅读(159)  评论(0编辑  收藏  举报