每3日一篇leetcode,第二題:LongestSubstringWithoutRepeatingCharacters

1.尋找最長沒有重複的子串

//82 ms	38.2 MB
    public int lengthOfLongestSubstring(String s) {
        int maxNum = 0;
        for (int i = 0, size = s.length(); i < size; i++) {
            for (int j = i + 1; j <= size; j++) {
                String temp = s.substring(i, j);
                if (j == size) {
                    maxNum = Math.max(size - i,maxNum);
                } else if (temp.indexOf(s.charAt(j)) != -1) {
                    if (temp.length() > maxNum) {
                        maxNum = temp.length();
                    }
                    break;
                }
            }
        }
        return maxNum;
    }


    //10 ms	37.2 MB
    public int lengthOfLongestSubstring2(String s) {
        int maxNum = 0;
        LinkedList<Character> linkedList = new LinkedList<>();
        int i = 0, j = 0, size = s.length();
        while (i < size && j < size) {
            char at = s.charAt(j);
            if (linkedList.contains(at)) {
                linkedList.remove((Object) s.charAt(i));
                i++;
            } else {
                linkedList.add(at);
                j++;
                maxNum = Math.max(j - i, maxNum);
            }

        }
        return maxNum;
    }
複製代碼
相關文章
相關標籤/搜索