剑指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     }

 

转载于:https://www.cnblogs.com/ChenXionghfut/p/8442862.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值