Leetcode 3 Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

使用Hash存储已经读入的字符,一个指针用于读入字符并存入Hash,发现Hash中存在相同字符后,另一个指针向前移动并删除Hash中之间的字符直至保持该监测到的字符唯一,并维护最大值。

def length_of_longest_substring(s)
    h = Hash.new
    max, i = 0, 0
    s.length.times do |j|
        while h[s[j]]
            h.delete(s[i])
            i += 1
        end
        h[s[j]] = 1
        max = j-i+1 > max ? j-i+1 : max
    end
    max
end

 

posted @ 2015-06-11 16:05  lilixu  阅读(113)  评论(0编辑  收藏  举报