- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
这是一道DP题,使用DP[i]来表示以I为结尾的子串的最大长度。转移关系式式
DP[i+1]=Math.min(DP[i]+1,i-j),j是距离I+1最近的相同结点的位置。由于DP[i+1]只由前一个状态决定,上面的表达式可以写成迭代的形式。
class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character,Integer> map = new HashMap<>();
if(s==null||s.length()==0) return 0;
int max = 0;
int j =0 ;
for(int i = 0 ;i<s.length();i++)
{
char ch = s.charAt(i);
if(map.containsKey(ch))
{
int start = map.get(ch);
j = Math.min(j+1,i-start);
}
else
{
j++;
}
max=Math.max(j,max);
map.put(ch,i);
}
return max;
}
}
网友评论