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

【LeetCode】Longest Substring Without Repeating Characters

时间:2015-06-26 16:22:02      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:leetcode   longest   substring   

问题描述

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.

Input:abcabcbb
Output:3

意:查找给定字符串中最长的无重复字符的子串

算法思想

对于字符串S<a1,a2,a3,a4,a3>,如果我们从左向右扫描字符串,那么当遇到第二个a3时,对于a4及其之前的所有子串的长度一定小于等于a4。所以不必要每次从头查找子串。
如果没有重复字符,那么i=0,j=n, 长度为j-i+1
如果存在重复字符,那么长度为j-i(不包含重复字符本身),然后我们将i更新为重复字符中的第一个,上例中当遇到第二个a3时,i=2。
如果我们使用hashmap判断重复字符的出现,需要判断重复字符是否出现在i与j之间。

算法实现

import java.util.HashMap;
public class Solution {
    public static int lengthOfLongestSubstring(String s) {
        int i = 0;
        int j = 0;
        int loc = 0;
        int nowCount = 0, tmpCount = 0;
        HashMap<Character, Integer> holder = new HashMap<Character, Integer>();
        int n = s.length();
        while (j < n) {
            Character c = s.charAt(j);
            if (!holder.containsKey(c) || (loc = holder.get(c)) < i) {
                tmpCount = j - i + 1;
            } else {
                tmpCount = j - i;
                i = loc + 1;
            }
            nowCount = tmpCount > nowCount ? tmpCount : nowCount;
            holder.put(c, j);
            j++;
        }
        return nowCount;
    }

    public static void main(String[] args) {
        String s = "abcabc";
        System.out.println(lengthOfLongestSubstring(s));
    }
}

算法时间

T(n) = O(n);//忽略hash查找的时间

演示结果

3

【LeetCode】Longest Substring Without Repeating Characters

标签:leetcode   longest   substring   

原文地址:http://blog.csdn.net/baidu_22502417/article/details/46650317

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