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;
    }
}

猜你喜欢

转载自www.cnblogs.com/tobeabetterpig/p/9454886.html
今日推荐