题解 | #最长不含重复字符的子字符串#
最长不含重复字符的子字符串
http://www.nowcoder.com/practice/48d2ff79b8564c40a50fa79f9d5fa9c7
解题思路
感觉这道题是动态规划和hashmap 的结合题。用hashmap 存储不重复字符及其出现的位置。dp[i] 表示以i 结尾的最长不含重复字符的子字符长度。i 位置的字符不在hashmap 中,动态转移方程:dp[i]=dp[i-1]+1,并将其加入到hashmap中,如果在i为的字符在hashmap 中,则获取其的位置pos。dp[i]=i-pos。 注意在第二种情况下,需要将hashmap进行清空。将pos到i 的位置的字符加入到hashmap中 。这是我在debug时候才发现的问题。
代码实现
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型
*/
public static int lengthOfLongestSubstring (String s) {
//这个方法有问题
int lens=s.length();
if(lens<1){
return 0;
}
//存储中间结果
int[] dp = new int[lens];
// 定义一个hashmap 存储不重复字符及其出现的位置
HashMap<Character, Integer> hashmap = new HashMap<>();
dp[0]=1;
hashmap.put(s.charAt(0),0);
for(int i=1;i<lens;i++){
//hashmap 中没有
if(!hashmap.containsKey(s.charAt(i))){
hashmap.put(s.charAt(i),i);
dp[i]=dp[i-1]+1;
}else{
// hashmap 中有, 获取位置
int pos = hashmap.get(s.charAt(i));
dp[i]=i-pos;
//更新当前字符的位置
//要将hashmap 中pos 到i 的char 放入hashmap 中 debug 时候才发现问题
hashmap.clear();
for(int j=pos+1;j<=i;j++){
hashmap.put(s.charAt(j),j);
}
}
}
int result=Integer.MIN_VALUE;
for(int i=0;i<lens;i++){
if(dp[i]>result){
result=dp[i];
}
}
return result;
}
}