部分文章内容为公开资料查询整理,原文出处可能未标注,如有侵权,请联系我,谢谢。邮箱地址:gnivor@163.com ►►►需要气球么?请点击我吧!

LeetCode--3. Longest Substring Without Repeating Characters

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.

大意:给出一个字符串,寻找最长不重复子串,求其长度。如"abcabcbb"最长不重复子串为"abc",长度为3. "bbbbbb"最长不重复子串为"b",长度为1

方法1:双层循环解决。每增加一个字符,就将字符从后向前和前面所有的字符比较,看是否相等。如果有相等的,那么就从相等的那个元素后一个元素开始进行比较

public static int lengthOfLongestSubstring(String s) {
    int maxnum = 1;
    int num=1;        
    int start = 0; 
    
    int len = s.length();
    if(len==0)
        return 0;
    for(int i = 1 ; i <len ; i++){
        num =1;
        char c = s.charAt(i);
        for(int j=i-1; j>=start ; j--){
            if(c==s.charAt(j)){
                start = j+1;
                break;
            }else{
                num++;
            }
        }
        if (maxnum<num)
            maxnum = num;
    }
    
    return maxnum;
}

 

方法2:HashMap,key为字符,value为元素位置。详细见注释。

public static int lengthOfLongestSubstring(String s) {
    int maxnum = 0; //最长长度
    int num=0;    //当前长度
    HashMap<Character,Integer> map = new HashMap();
    int start = 0; //开始位置
    Integer temp = null; //下标
    int len = s.length();
    for(int i = 0 ; i <len ; i++){
        char c = s.charAt(i);  //获取字符
        temp = (Integer) map.get(c); //在map中寻找c
        if(temp==null){ //如果不存在,添加进去,长增1
            map.put(c, i);
            num++;
        }
        else{    //如果map中已经存在,但是是在当前的起始位置之前,可视为不重复,重新设置下标,长度增1
            if(temp<start){
                map.put(c, i);
                num++;
            }
            else{    //如果确实重复,那么起始位置更新为重复元素的下一个元素
                start=temp+1;
                map.put(c, i);     //更新下标
                num = i -start+1;
            }
        }
        if(num>maxnum)
            maxnum = num;
    }    
    return maxnum;
}

 

posted @ 2015-07-09 17:26  流了个火  阅读(126)  评论(0)    收藏  举报
►►►需要气球么?请点击我吧!►►►
View My Stats