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

【LeetCode】Longest Substring Without Repeating Characters

时间:2017-07-21 22:12:31      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:line   tmp   算法实现   使用   abc   字符   class   splay   eating   

问题描写叙述

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

标签:line   tmp   算法实现   使用   abc   字符   class   splay   eating   

原文地址:http://www.cnblogs.com/jzdwajue/p/7219631.html

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