码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】3. Longest Substring Without Repeating Characters

时间:2016-04-10 12:54:35      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

计算最长的无重复字符的串长

用HashMap记住重复的单词及其位置。当重复时,让tempStart指针移到重复位置+1,如果start指针小于tempStart,则更新start指针,长度就是当前重复的位置 - start。读到字符串末尾时还需要判断一次

 

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        int start = 0;
        int maxLength = 0;
        for (int i = 0; i < s.length(); ++i) {
            char c = s.charAt(i);
            if (map.containsKey(c)) {
                int length = i - start;
                int tempStart = map.get(c) + 1;
                start = start > tempStart ? start : tempStart;
                if (maxLength < length) {
                    maxLength = length;
                }
            }
            map.put(c, i);
        }
        int length = s.length() - start;
        if (maxLength < length) {
            maxLength = length;
        }
        return maxLength;
    }
}

 

【leetcode】3. Longest Substring Without Repeating Characters

标签:

原文地址:http://www.cnblogs.com/lanhj/p/5373674.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!