03.Longest Substring without repeating characters

Source: Internet
Author: User

Longest Substring without repeating characters (longest substring not repeating character)

title: Given a string, the length of the longest substring is found, requiring no repetition of characters.

For example:

  Given a string "ABCABCBB", the answer is "ABC", the length is 3.

Given a string "bbbbb", the answer is "B" and the length is 1.

Given a string "Pwwkew", the answer is "Wke", the length is 3.

  Note: The answer must be a substring, and "Pwke" is a sub-sequence, not a substring.

Solution One:

Idea: The basic idea is to create a hash table to store the characters in the string. The character is the key and the position is the value. Set two value start,end to scan the string while updating the hash table. If the character already exists in the hash list, the start value is updated and the start value is assigned to the right of the last found character.

1  Public classLongestsubstringwithoutrepeatingcharacters {2     3      Public Static voidMain (string[] args) {4Scanner Scanner =NewScanner (system.in);5String string =scanner.nextline ();6System.out.println ("The length of the longest non-repeating substring is:" +lengthoflogestsubstring (String));7     }8 9     Ten      Public Static intlengthoflogestsubstring (String s) { One         intMax = 0; AMap<character, integer> map =NewHashmap<>(); -          for(intStart = 0,end = 0; End < S.length (); end++) { -             if(Map.containskey (S.charat (end))) { theStart = Math.max (Start, Map.get (S.charat (end)) +1); -             } - Map.put (S.charat (end), end); -max = Math.max (max, end-start+1); +         } -         returnMax; +     } A}

03.Longest Substring without repeating characters

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.