首页 > 其他 > 详细

【leetcode】3. Longest Substring Without Repeating Characters

时间:2016-04-10 12:54:15      阅读:183      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!