题解 | #最长不含重复字符的子字符串#

最长不含重复字符的子字符串

http://www.nowcoder.com/practice/48d2ff79b8564c40a50fa79f9d5fa9c7


思路:
dp[i]表示的是以i结尾的最长不含重复字符的子字符串。使用了hashmap这个数据结构记录<char,index>
如果map中没有当前这个元素,那么dp[i]=dp[i-1]+1
如果map中存在当前的元素,一开始的想法是 dp[i]=i-map.get(array[i]),但是这样想有点问题,如果当前的字符串是abba的时候,按照刚才的思路dp[0]=1 dp[1]=2 dp[2]=1 dp[3]=3
但是dp[3]是错误的,因为中间存在了重复的字符。所以要加一种情况。
dp[i]=Math.min(dp[i-1]+1,i-map.get(array[i]))

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return int整型
     */
    public int lengthOfLongestSubstring (String s) {
        if(s==null) return 0;
        char[]array=s.toCharArray();
        if(array.length==1){
            return 1;
        }
        int[]dp=new int[array.length];
        int maxLength=1;
        HashMap<Character, Integer>map=new HashMap<>();
        dp[0]=1;
        map.put(array[0],0);
        for(int i=1;i<array.length;i++){
            dp[i]=1;
            if(!map.containsKey(array[i])){
                dp[i]=dp[i-1]+1;
            }
            else{
                dp[i]=Math.min(dp[i-1]+1,i-map.get(array[i]));
            }
            map.put(array[i],i);
            maxLength=Math.max(maxLength,dp[i]);
        }
        return maxLength;
    }
}
全部评论

相关推荐

陆续:不可思议 竟然没那就话 那就我来吧 :你是我在牛客见到的最美的女孩
点赞 评论 收藏
分享
06-20 17:42
东华大学 Java
凉风落木楚山秋:要是在2015,你这简历还可以月入十万,可惜现在是2025,已经跟不上版本了
我的简历长这样
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
16
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务