Leetcode刷题日记 -- Longest Substring Without Repeating Characters

来源:互联网 发布:数据库工程师考试科目 编辑:程序博客网 时间:2024/06/07 09:46

先贴题:

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.


这个题目思路比较简单,即使用两个指针寻找不重复的子字符串,从头到尾遍历一遍即可找到。时间复杂度O(n),由于是字符,可以使用数组记录(有意义的字符是从‘ ‘ -> '~', askii 30-125)在哪个位置字符出现过。空间复杂度为O(95). 之前的测试用例只有小写字母。

算法思路:

初始化:首尾start,end指针指向字符串第一个字符。创建一个长度为95,每项都为-1的hash数组

对于每一个新加进来的尾字符str.charAt(end):

若(1)此字符在之前出现过(2)且出现位置在头指针之后,则出现重复,需把头指针指向重复位置的下一个字符。

若没有出现过或出现位置在头指针之前,则未出现重复,将此字符的最新位置更新至hash数组中。若长度比之前的最大长度max大,更新最大长度max。

尾指针end+1;


注意的点:

判断条件需两点要出现过并且是在start和end中间的位置出现,不然不算出现。如 a,b,b,c,a,d,e 在end指向第二个a的时候,不能算重复。


贴代码:

public class Solution {    public int lengthOfLongestSubstring(String s) {                HashMap<Character,Integer> hash = new HashMap<Character,Integer>();        int start = 0;        int end = 0;        int len = 0;        int max = 0;        int[] has = new int[95];        for(int i = 0; i < 95; i++){            has[i] = -1;        }        while(end < s.length()){            char c = s.charAt(end);            if(has[c-' '] != -1 && has[c-' '] >= start){            start = has[c-' '] + 1;                len = end - start + 1;                has[c-' '] = end;                end++;            }else{                has[c-' '] = end;                len++;                if(len > max)max = len;                end++;            }        }        return max;    }    }


0 0
原创粉丝点击