您的位置:首页 > 其它

LeetCode.3 Longest Substring Without Repeating Characters(动态规划求解,***经典必备题***)

2018-03-06 16:10 288 查看
题目:

Given a string, find the length of the longest substring without repeating characters.
Examples:
Given
"abcabcbb"
, the answer is
"abc"
, which the length is 3.
Given
"bbbbb"
, the answer is
"b"
, with the length of 1.
Given
"pwwkew"
, the answer is
"wke"
, with the length of 3. Note that the answer must be a substring,
"pwke"
is a subsequence and not a substring.
分析:class Solution {
public int lengthOfLongestSubstring(String s) {
//最长字符串不包含重复的长度
//思路:典型的递归问题,即f(i)=f(i-1)+1,其中表示以i结尾的字符串不重复长度
//分情况分析:1.当前面存在和i相同的字符串,那么它们俩之间的长度为d 如果d>f(i-1) 说明重复的在前一个字符串的最长不重复字符前面,不影响
//f(i)=f(i-1)+1。2.如果d<f(i-1),说明在前面i-1不重复的字符里面,那么更新f(i)=d,这是i不重复子串的长度

//Hint:使用数组来记录各字符,字符可能为256个最后次出现的下标

//curLength用来记录i-1的长度
int curLength=0;
int maxLength=0;
if(s.length()==0||s==null) return maxLength;

//初始化,256个字符均没有出现过,用-1表示
int [] alpha=new int[256];
Arrays.fill(alpha,-1);

for(int i=0;i<s.length();i++){
//字符之前的下表
int preIndex=alpha[s.charAt(i)];
if(preIndex<0||i-preIndex>curLength){
//说明,对更新结果不受影响
curLength++;
}else{
//重复长度小于,说明f(i)=d
curLength=i-preIndex;
}

//更新最新出现的下表
alpha[s.charAt(i)]=i;
maxLength=Math.max(maxLength,curLength);
}
return maxLength;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: