3 Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: 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.

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

 

posted on 2018-11-08 02:12  猪猪&#128055;  阅读(93)  评论(0)    收藏  举报

导航