LeetCode Longest Substring Without Repeating Characters

来源:互联网 发布:软件工程硕士培养方案 编辑:程序博客网 时间:2024/05/22 06:30

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.

题意:给出一个字符串,求最大的子串,其中子串中字符没有重复的。

思路:在遍历过程中,如果以前没有出现过,加入hashset中。如果有重的,就将开始位置到第一次出现之间(包含)的字符从hashset中去掉。

代码如下:

class Solution{    public int lengthOfLongestSubstring(String s)    {        int ans = 0;        Set<Character> hs = new HashSet<Character>();        int start = 0;        for (int i = 0; i < s.length(); i++)        {            if (hs.contains(s.charAt(i)))            {                while (start < i && s.charAt(start) != s.charAt(i))                {                    hs.remove(s.charAt(start));                    start++;                }                start++;                hs.remove(s.charAt(i));            }            hs.add(s.charAt(i));            ans = Math.max(ans, hs.size());        }        return ans;    }}


0 0
原创粉丝点击