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