您的位置:首页 > 其它

Leetcode 3 Longest Substring Without Repeating Characters

2015-06-11 16:05 477 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: