003_LongestSubstringWithoutRepeatingCharacters

/***
 *
 * Given a string, find the length of the longest substring without repeating characters.
 *
 * Example 1:
 *
 * Input: "abcabcbb"
 * Output: 3
 * Explanation: The answer is "abc", with the length of 3.
 * Example 2:
 *
 * Input: "bbbbb"
 * Output: 1
 * Explanation: The answer is "b", with the length of 1.
 * Example 3:
 *
 * Input: "pwwkew"
 * Output: 3
 * Explanation: The answer is "wke", with the length of 3.
 *              Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
 *
 *
 */
/***
* 关键:
* 先遍历一遍放进hashmap,所以复杂度是O(n)
*
*/
public class N003_LongestSubstringWithoutRepeatingCharacters {
        /***
     * 使用HashMap记录字符上次出现的位置
     * 用pre记录最近重复字符出现的位置
     * 则i(当前位置)-pre就是当前字符最长无重复字符的长度
     * 取最大的就是字符串的最长无重复字符的长度
     *
     * 时间复杂度:O(n)
     */
    public static int lengthOfLongestSubstring(String str) {
        if (str == null || str.length() < 1)
            return 0;

        // 记录字符上次出现的位置
        HashMap<Character, Integer> map = new HashMap<>();
        int max = 0;
        // 最近出现重复字符的位置
        int pre = -1;

        for (int i = 0, strLen = str.length(); i < strLen; i++) {
            Character ch = str.charAt(i);
            Integer index = map.get(ch);
            if (index != null)
                pre = Math.max(pre, index);     //这一步很关键,取前一个相同字符位置,而不是后一个;后一个字符还有可能成为字串的元素
            max = Math.max(max, i - pre);
            map.put(ch, i);
        }

        return max;
    }

    public static void main(String args[]) {
        String input = "nevereverbeacoder";

        int len = lengthOfLongestSubstring(input);
        System.out.println(len);

    }
}
本站公众号
   欢迎关注本站公众号,获取更多信息