[Leetcode click Notes] Longest substring without repeating characters

Source: Internet
Author: User

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.

 

Question: greedy algorithm.

Use a hashmap to store the elements of the longest unduplicated substring. The variable leftbound stores the leftmost boundary of the current state. The character s [I] currently traversed has two situations:

  1. S [I] indicates that the element already exists in the map, so move leftbound left until leftbound reaches I, this section does not contain S [I], in addition, the elements scanned by leftbound are cleared in map;
  2. The elements referred to by S [I] are not in the map. Keep leftbound unchanged and check whether the length of the longest substring needs to be updated.

The Code is as follows:

 1 public class Solution { 2     public int lengthOfLongestSubstring(String s) { 3         if(s == null || s.length() == 0) 4             return 0; 5              6         HashMap<Character, Integer> map = new HashMap<Character, Integer>(); 7         int leftebound = 0; 8         int answer = 0; 9        10         for(int i = 0;i < s.length();i++){11             char current = s.charAt(i);12             if(map.containsKey(s.charAt(i))){                13                 while(s.charAt(leftebound) != current && leftebound < i){14                     map.remove(s.charAt(leftebound));15                     leftebound++;16                 }17                 leftebound++;18             }19             else {20                 map.put(current, 0);21                 answer = Math.max(i-leftebound+1, answer);22             }23         }24         25         return answer;    26     }27 }       

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.