Problem:Given A string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "ABCABCBB" are "abc", which the length is 3. For "bbbbb" the longest substring are "B", with the length of 1.
Solution:NoMain topic:test instructions is simpler, given a string that requires the length of the oldest string, and the substring requires no repeating characters. Problem Solving Ideas:can be solved by hash storage + dynamic programming, walking from left to right, marking the leftmost position of the substring, when a repeating character is encountered, the current substring has ended, a new string is started, the position of the character is updated, and the left of the substring. Java source code:
public class Solution {public int lengthoflongestsubstring (String s) { int left=0,max=0; map<character,integer> map = new hashmap<character,integer> (); char[] CHS = S.tochararray (); for (int i=0;i<chs.length;i++) { if (Map.containskey (Chs[i]) && map.get (Chs[i]) >=left) {Left = Map.get (Chs[i]) +1; } Map.put (chs[i],i); Max = max> (i-left+1)? Max: (i-left+1); } return Max;} }
C Language Source code:
#include <limits.h> #include <stdio.h>int lengthoflongestsubstring (char* s) { int i,j,left=0,max=0, HASH[256]; for (j=0;j<256;j++) Hash[j]=int_max; for (i=0;s[i];i++) { if (Hash[s[i]]!=int_max && hash[s[i]]>=left) left=hash[s[i]]+1; hash[s[i]]=i; Max = max> (i-left+1)? Max: (i-left+1); } return Max;}
C + + source code:
Class Solution {public: int lengthoflongestsubstring (string s) { int max=0,left=0; map<int,int> map; for (int i=0;i<s.size (); i++) { std::map<int,int>::iterator iter=map.find (S[i]); if (Iter!=map.end () && Iter->second >=left) { left=iter->second+1; } map[s[i]]=i; Max = max> (i-left+1)? Max: (i-left+1); } return Max; };
python source code:
Class solution: # @param {string} s # @return {integer} def lengthoflongestsubstring (self, s): left=0< C4/>max=0 hash={} for I in range (len (s)): ch = s[i] if Hash.has_key (CH) and Hash[ch]>=left: Left=hash[ch]+1 hash[ch]=i max= Max if max>i-left+1 else i-left+1 return Max
Leetcode 3 longest Substring without repeating characters