leetcode #3 Longest Substring Without Repeating Characters

来源:互联网 发布:阿里云空间申请 编辑:程序博客网 时间:2024/05/22 13:24

这题卡了很久才做出来。
主要问题在于当输入与hashmap中已有的数据相同的字母时,还要判断重复是不是发生在目前的length范围内。
如String abcbca
当最后一个a进入时,当前的length范围是“bc”,不过不加以处理,程序会误以为当前hashmap中的a是一个重复进而i-measure.get(s.charAt(i))=5-0=5
而实际上之前的a已经第二个b输入时就已经被排出length范围了,不应该计算在内。

Update:
其实value就是每个字母在数组中最后出现的位置

public class Solution {    public int lengthOfLongestSubstring(String s) {        int length=0,max=0,i;        if(s.length()==1)return 1;        char[] input = s.toCharArray();        Map<Character, Integer> measure = new HashMap<Character, Integer>();        for(i=0;i<input.length;i++){            if(measure.containsKey(input[i])&&(i-measure.get(input[i]))<=length){                length=i-measure.get(input[i]);            }            else length++;            measure.put(input[i], i);            max=Math.max(max, length);        }        return max=Math.max(max, length);    }}

Fight On!

0 0
原创粉丝点击