• [Leet code 3]Longest Substring Without Repeating Characters


    1 题目

    Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

    Hide Tags
     Hash Table Two Pointers String
     
    2 思路
    开始想的是取得所有不重复的不就行了,后来发现要连续子串。
    然后想着每当碰到重复的,就从该点下一位开始重新添加。
    后来碰到个bug测试输入,时间超时。
     
     
    看到别人的思路,使用了题目提示的Two Pointers。并且,table的key,value设置有讲究,key是字母,value是位置。与我开始想的key是位置不一样。
    原文链接:
    ok,见代码
     
    3 代码
           public int lengthOfLongestSubstring(String s) {
               Hashtable<Character,Integer> hash=new Hashtable<>();
               int length=s.length();
               int max=0;
               int availablefrom=0;
               for(int i=0;i<length;i++){
                   if(hash.containsKey(s.charAt(i))){
                       //int last = the largest index where has the same character (before current index i)
                       int last=(Integer) hash.get(s.charAt(i));
                       //int available-from = the next index from where latest duplication ends (before current index i)
                       //之所以取最大,防止出现abba,遍历到第二个a时,last会比availableform小
                       availablefrom=Math.max(availablefrom, last+1);
                   }
                 //then the possible substring is located between available-from and i。
                   max=Math.max(max, i-availablefrom+1);
                   hash.put(s.charAt(i),i);        
               }
               return max;
            }
  • 相关阅读:
    053587
    053586
    053585
    053584
    053583
    053582
    053581
    053580
    053579
    053578
  • 原文地址:https://www.cnblogs.com/lingtingvfengsheng/p/4432719.html
Copyright © 2020-2023  润新知