3. Longest Substring without repeating characters "Leetcode" Java, algorithm, Substring implementation, SUBSTRING, HASHMAP

Source: Internet
Author: User

3. Longest Substring without repeating characters

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb" , the answer "abc" is, which the length is 3.

Given "bbbbb" , the answer "b" is, with the length of 1.

Given "pwwkew" , the answer "wke" is, with the length of 3. Note that the answer must was a substring, is "pwke" a subsequence and not a substring.

Problem:

Given a string, the length of the longest substring is found without repeating characters.
Instance:
"ABCABCBB", the answer is "ABC", its length is 3.
"BBBBB", the answer is "B", the length is 1.
"Pwwkew", the answer is "Wke", to 3 of the length. Note that the answer must be a string, and "Pwke" is a substring.

Implementation method:

1. Get the string length
2. Record the current value is left mark
3. Determine if the current letter has occurred, and if so, update the current position to a new left tag
4. Update res length If current value is larger than res

Method: Use HashMap to skip loops and save time and space when you encounter duplicates

1  Public classSolution {2      Public intlengthoflongestsubstring (String s) {3map<character,integer> map =NewHashmap<>();4         intRes =0,len=s.length ();5          for(inti=0,j=0;j<len;j++){6             if(Map.containskey (S.charat (j))) {7I=Math.max (Map.get (S.charat (j)), I);8             }9Map.put (S.charat (j), j+1);TenRes =math.max (j-i+1, res); One         } A         returnRes; -     } -}

3. Longest Substring without repeating characters "Leetcode" Java, algorithm, Substring implementation, SUBSTRING, HASHMAP

Related Article

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.