soapyigu/LeetCode-Swift

"Longest Substring Without Repeating Characters", answer is wrong!

vmjie opened this issue · 3 comments

vmjie commented

use "abcdefghiepoiuq" to test, print 9. but 10 Actually.

My code prints correctly:

    func lengthOfLongestSubstring(_ string: String) -> Int {
        var flags = Array(repeating: -1, count: 128)
        var maxLength = 0
        var startIndex = -1
        
        for (index, char) in string.enumerated() {
            let asciiValue = Int(char.asciiValue ?? 0)
            if flags[asciiValue] > startIndex {
                if index - startIndex > maxLength {
                    maxLength = index - startIndex
                }
                startIndex = flags[asciiValue] + 1
                flags[asciiValue] = index
                continue
            }
            flags[asciiValue] = index
        }
        
        if string.count - startIndex > maxLength {
            maxLength = string.count - startIndex
        }
        return maxLength
    }

Let me look into that. Thanks for your feedback.

Hi why the answer is 10 for "abcdefghiepoiuq"? I think the longest sub-string without repeating character is "abcdefghi".

vmjie commented

so sorry. Your code is running correctly.I should be more careful.

It runs correctly,when I modified it to:

    func lengthOfLongestSubstring(_ string: String) -> Int {
        var flags = Array(repeating: -1, count: 128)
        var maxLength = 0
        var startIndex = 0

        for (index, char) in string.enumerated() {
            let asciiValue = Int(char.asciiValue!)
            if flags[asciiValue] >= startIndex {
                if index - startIndex + 1 > maxLength {
                    maxLength = index - startIndex
                }
                startIndex = flags[asciiValue] + 1
            }
            flags[asciiValue] = index
        }

        if string.count - startIndex > maxLength {
            maxLength = string.count - startIndex
        }
        return maxLength
    }