3 Longest Substring Without Repeating Characters

Posted tobeabetterpig

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3 Longest Substring Without Repeating Characters相关的知识,希望对你有一定的参考价值。

3 Longest Substring Without Repeating Characters

https://www.youtube.com/watch?v=dH5t6rWmob0


template 
https://leetcode.com/problems/minimum-window-substring/discuss/26808/here-is-a-10-line-template-that-can-solve-most-substring-problems

有好多答案模版, 找个适合自己的,先自己写写



class Solution {
    public int lengthOfLongestSubstring(String s) {
      int begin = 0;
      int end = 0;
      int repeat = 0;
      int max = 0;
      int[] hash = new int[256]; /////. int[] hash, value is integer, index is char 
      while(end < s.length()){
  
        if(hash[s.charAt(end)] > 0){
          repeat++;
        }
        hash[s.charAt(end)]++;
        end++;
        
        while(repeat > 0){
          if(hash[s.charAt(begin)] > 1){
            repeat--;
          }
          hash[s.charAt(begin)]--;
          begin++;
        }
        
        max = Math.max(max, end - begin);
        
      }
      return max;
    }
}


// same code for the while block, different writing style 
while(end < s.length()){
  if(hash[s.charAt(end++)]++ > 0){
    repeat++;
  }
  while(repeat > 0){
    if(hash[s.charAt(begin++)]-- > 1){
      repeat--;
    }
  }
  max = Math.max(max, end - begin);
}




// ????
//when I change  (hash[s.charAt(end).  to       hash[s.charAt(end) - ‘a‘]
// s: Runtime Error


class Solution {
    public int lengthOfLongestSubstring(String s) {
      int begin = 0;
      int end = 0;
      int repeat = 0;
      int max = 0;
      int[] hash = new int[26]; /////. int[] hash, value is integer, index is char 
      while(end < s.length()){
  
        if(hash[s.charAt(end) - ‘a‘]> 0){
          repeat++;
        }
        hash[s.charAt(end) - ‘a‘]++;
        end++;
        
        while(repeat > 0){
          if(hash[s.charAt(begin) - ‘a‘] > 1){
            repeat--;
          }
          hash[s.charAt(begin) - ‘a‘]--;
          begin++;
        }
        
        max = Math.max(max, end - begin);
        
      }
      return max;
    }
}

 

以上是关于3 Longest Substring Without Repeating Characters的主要内容,如果未能解决你的问题,请参考以下文章

3. Longest Substring Without Repeating Charactersleetcodejava,算法,Substring实现,子串,HashMap

Leetcode 3. Longest Substring Without Repeating Characters

LeetCode 3. Longest Substring Without Repeating

#3 Longest substring without repeating characters

3. Longest Substring Without Repeating Characters

3. Longest Substring Without Repeating Characters