3. 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.

链接: http://leetcode.com/problems/longest-substring-without-repeating-characters/

题解:

Sliding Window,每次在HashMap里放入当前字符的index i。 要注意start何时更新。 比如abba这种情况。 Time Complexity - O(n),Space Complexity - O(n)

public class Solution {

    public int lengthOfLongestSubstring(String s) {

        if(s == null || s.length() < 2)

            return s.length();

        int max = 0, start = 0;

        HashMap<Character, Integer> map = new HashMap<Character, Integer>();

        

        for(int i = 0; i < s.length(); i++){

            if(map.containsKey(s.charAt(i)))

                if(map.get(s.charAt(i)) >= start)

                    start = map.get(s.charAt(i)) + 1;

            map.put(s.charAt(i), i);

            max = Math.max(max, i - start + 1);

        }

        

        return max;

    }

}

 

你可能感兴趣的:(substring)