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.
Solution:
public class Solution {
public int lengthOfLongestSubstring(String s) {
int lastRepeating = -1;
int longestSubstring = 0;
HashMap<Character, Integer> positions = new HashMap<Character, Integer>();
for(int i=0; i<s.length(); i++)
{
if(positions.containsKey(s.charAt(i)) && positions.get(s.charAt(i))>lastRepeating)
lastRepeating = positions.get(s.charAt(i));
if(i-lastRepeating > longestSubstring)
longestSubstring = i-lastRepeating;
positions.put(s.charAt(i),i);
}
return longestSubstring;
}
}
No comments :
Post a Comment