Longest Substring Without Repeating Characters

来源:互联网 发布:php怎么文件上传 编辑:程序博客网 时间:2024/06/03 16:01

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.


public class Solution {

    public int lengthOfLongestSubstring(String s) {
        if(s == null || "".equals(s))
    return 0;
    char[] chars = s.toCharArray();
    Map map = new HashMap(chars.length);    
    int index1 = 0, index2 = 0,subLength = 0; 
    for(int i = 0; i < chars.length; i++){
    if(map.containsKey(chars[i]) && (Integer)map.get(chars[i]) >= index1){ 
    int len = index2 - index1 + 1;
        if(len > subLength){
        subLength = len;
        }  
    index1 = (Integer)map.get(chars[i])+1;     
    }else{
    index2 = i;
    }      
    map.put(chars[i],i);
    }    
    int len = index2 - index1 + 1;
    if(len > subLength){
    subLength = len;
    }
    return subLength;          
    }
}
0 0