[LeetCode-Java]3. 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.

解:使用HashSet判断是否包括相同元素。注意比较到最后一位的处理。

public static int lengthOfLongestSubstring(String s) {

        int length = 0;

        HashSet  set = new HashSet<>();

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

            set.clear();
            while (true){
                //当因为到达最后一位而退出,最高值肯定在之前的值产生,不需要进行后续比较。
                if (j == s.length())  return set.size() > length ? set.size() :  length;
                if (!set.contains(s.charAt(j))){
                    set.add(s.charAt(j));
                    j++;
                }else {
                    if (set.size() > length) length = set.size();
                    break;
                }
            }


        }

        return length;

    }

你可能感兴趣的:(LeetCode)