leetcode3---Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", 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.
题目分析:给出一个字符串,求出它没有重复字符的最长长度。我们当然可以用两重循环,找出最长无重复字符的长度。这种显然不是我们期望的。我们可以用一个map来实现,map保存的key-val值为string中字符的值以及它上一次出现的位置,index表示没有重复字符字符串的首字符位置,i代表没有重复字符字符串的最右位置。每次遍历到i时,如果map不包含s.charAt(i),则计算长度i-len+1,否则,更新index位置。然后再计算长度。一次遍历之后就可以得到结果。

public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0)
            return 0;
        if (s.length() == 1)
            return 1;
        HashMap map = new HashMap<>();
        int result = 0;
        int index = 0;
        for (int i = 0; i < s.length(); i++) {
            if (map.containsKey(s.charAt(i))) {
                index = Math.max(index, 1 + map.get(s.charAt(i)));
            }
            int len = i - index + 1;
            map.put(s.charAt(i), i);
            result = Math.max(len, result);
        }
        return result;
    }

你可能感兴趣的:(leetcode3---Longest Substring Without Repeating Characters)