您的位置:首页 > 其它

LeetCodeOJ.Longest Substring Without Repeating Characters

2015-10-08 14:03 447 查看
试题请参见: https://leetcode.com/problems/longest-substring-without-repeating-characters/

题目概述

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.

解题思路

The idea is use a hash set to track the longest substring without repeating characters so far, use a fast pointer j to see if character j is in the hash set or not, if not, great, add it to the hash set, move j forward and update the max length, otherwise, delete from the head by using a slow pointer i until we can put character j to the hash set.

简单地说, 解决这一类问题的基本思路是: 快慢指针. 正常情况下, 快指针一直向右移动, 并将所读到的字符放入HashSet中. 直到快指针所读到的字符在HashSet中已经出现, 记录此时快慢指针的差值并更新最大子串的长度. 同时, 在HashSet中删除慢指针所对应的字符, 直到快指针可以继续向右侧移动.

源代码

import java.util.HashSet;
import java.util.Set;

public class Solution {
public int lengthOfLongestSubstring(String s) {
int walker = 0, runner = 0, max = 0;
Set<Character> set = new HashSet<Character>();

while ( runner < s.length() ) {
if ( !set.contains(s.charAt(runner)) ) {
set.add(s.charAt(runner ++));
max = Math.max(max, set.size());
} else {
while ( set.contains(s.charAt(runner)) ) {
set.remove(s.charAt(walker ++));
}
}
}
return max;
}

public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.lengthOfLongestSubstring("bbbbb"));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: