【LeetCode】003.Longest Substring Without Repeating Characters

来源:互联网 发布:万方数据库检测 编辑:程序博客网 时间:2024/05/05 23:18

题目:

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.

解答:

基本思路:遍历字符串,遇到相同的字符,从上一个相同字符处的下一个位置重新开始遍历,计算本次遍历的最大长度,和历史最大长度比较。

方案一:

构造一个有序set,采用LinkedHashSet,遍历时,若当前值c存在于set中,则删除set中c之前(包括c)的所有元素,set.size()就是下一次遍历的字符串的初始长度,避免了回溯,但是增加了set的删除操作;


方案二:

方案一中,set的删除操作是为了获取下一次遍历字符串的初始长度,若每次存储字符时,记录其位置,可以通过位置差得到这个值,减去了set的删除操作。HashMap可以很容易做到这一点。

import java.util.*;public class Solution {   public int lengthOfLongestSubstring(String s) {Map<Character, Integer> map = new HashMap<Character, Integer>();int lastLongest = 0, curLongest = 0, curIndex = 0, lastChangedIndex = 0;for (char c : s.toCharArray()) {if (map.containsKey(c)) {lastLongest = Math.max(lastLongest, curLongest);int tempIndex = map.get(c);lastChangedIndex = Math.max(lastChangedIndex, tempIndex);curLongest = curIndex - lastChangedIndex - 1;}map.put(c, curIndex++);curLongest++;}return Math.max(lastLongest, curLongest);}}



0 0