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.
Java:
Solution 1:
public class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character,Integer> hashmap = new HashMap<Character,Integer>();
if(s.length() ==0) return 0;
int length = 0;
int max=0;
for(int i=0; i< s.length(); i++)
{
if(hashmap.get(s.charAt(i)) == null)
{
length ++;
hashmap.put(s.charAt(i),i);
}else
{
int k = hashmap.get(s.charAt(i));
if(length < i-k) length++;
else{
length = i-k;
}
hashmap.put(s.charAt(i), i);
}
max = max<length? length:max;
}
return max;
}
}
Solution 2:
public class Solution {
public int lengthOfLongestSubstring(String s) {
int globalMax = 0;
int tempMax = 0;
HashMap<Character,Integer> hashmap = new HashMap<Character,Integer>();
int i=0;
while( i<s.length())
{
if(hashmap.containsKey(s.charAt(i)))
{
int index = hashmap.get(s.charAt(i));
hashmap.clear();
tempMax = 0;
i = index+1;
}else
{
tempMax ++;
if(tempMax > globalMax)
globalMax = tempMax;
hashmap.put(s.charAt(i),i);
i++;
}
}
return globalMax;
}
}
solution 3:
public class Solution {
public int lengthOfLongestSubstring(String s) {
int maxLength = 0;
int tempLength = 0;
int startIndex = 0;
for(int i=0; i<s.length();i++)
{
if(s.indexOf(s.charAt(i),startIndex) >= i)
{
tempLength ++;
}else
{
tempLength = tempLength - (s.indexOf(s.charAt(i),startIndex) - startIndex) ;
startIndex = s.indexOf(s.charAt(i),startIndex) + 1;
}
if(tempLength > maxLength)
maxLength = tempLength;
}
return maxLength;
}
}