码迷,mamicode.com
首页 > 其他好文 > 详细

3 Longest Substring Without Repeating Characters

时间:2018-08-10 15:57:11      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:substr   col   erro   nbsp   hat   line   ems   char   ror   

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

标签:substr   col   erro   nbsp   hat   line   ems   char   ror   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9454886.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!