您的位置:首页 > 编程语言 > Java开发

【leetcode】【3】Longest Substring Without Repeating Characters

2016-02-27 09:53 405 查看

一、问题描述

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.

二、问题分析

该题是求字符串中不包括重复元素的最常子串的长度。从字符串的第一个元素开始分析,比如“abcabcbb”,此时子串为“a”,然后继续遍历字符串,此时碰到‘b’,因为子串中不包括,所以加到子串中,一次类推。当碰到‘a’时,此时子串中包括‘a’,因为是连续的,所以这里需要注意,我们要清理掉子串中‘a’包括‘a’之前的所有字符,并时刻记录子串的最大长度。这里很明显采用的是HashSet和双指针的策略。时间复杂度为O(n)。

三、Java AC代码

public int lengthOfLongestSubstring(String s) {
if (s==null||s.length()==0) {
return 0;
}
int fronter = 0;
int backer = 0;
int max = 0;
HashSet<Character> container = new HashSet<Character>();
while(fronter<s.length()){
if (container.contains(s.charAt(fronter))) {
if (fronter-backer>max) {
max = fronter - backer;
}
while(backer<fronter){
if (s.charAt(backer)!=s.charAt(fronter)) {
container.remove(s.charAt(backer));
backer++;
}else {
backer++;
break;
}
}
}else {
container.add(s.charAt(fronter));
}
fronter++;
}
return Math.max(max, fronter-backer);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode string