3. Longest Substring Without Repeating Characters

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.

 

题目含义:获取最长子串,要去子串中没有重复字符

 

方法一:

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 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 = Integer.MIN_VALUE;
        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;
    }
复制代码

 

 

方法二:

复制代码
 1     public int lengthOfLongestSubstring(String s) {
 2         if (s.length() == 0) return 0;
 3         HashMap<Character,Integer> map = new HashMap<>(); //记录每个字符最后一次出现的位置
 4         int max=0;
 5         int j=0;
 6         for (int i=0;i<s.length();i++)
 7         {
 8             char letter = s.charAt(i);
 9             if (map.containsKey(letter))
10             {
11                 j = Math.max(j,map.get(letter)+1); //j表示上一个letter后面的字符位置
12             }
13             map.put(letter,i);//记录每个字符最后一次出现的位置
14             max = Math.max(max,i-j+1);//上一个letter后面的字符到i的长度,也就是非重复子串的长度
15         }
16         return max;        
17     }
复制代码

 

posted @   daniel456  阅读(112)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示