【LeetCode OJ 003】Longest Substring Without Repeating Characters

題目鏈接:https://leetcode.com/problems/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.

解題思路:維護一個窗口,每次關注窗口中的字符串,維護一個HashSet,每掃描一個字符,如果HashSet中包含該字符,則移動左邊窗口至重複字符的下一個字符,如果HashSet中沒有改字符,則移動右邊窗口。時間負複雜度爲O(n),空間複雜度也爲O(n)。具體代碼如下:

public class Solution
{
    public static void main(String[] args)
    {
        String str="abcbbc";
        System.out.println(lengthOfLongestSubstring(str));
    }
    public static int lengthOfLongestSubstring(String s) 
    {
         if(s==null && s.length()==0)
                return 0;
            HashSet<Character> set = new HashSet<Character>();
            int max = 0;     //最大不重複字符串長度
            int left = 0;     //不重複字符串起始位置
            int right = 0;    //不重複字符串結束爲止
            while(right<s.length())
            {
                //如果集合中包含當前所指的字符
                if(set.contains(s.charAt(right)))
                {
                    //獲取當前不重複字符串的長度,如果大於max,則將max值替換
                    if(max<right-left)
                    {
                        max = right-left;
                    }
                    //將left移動到第一個重複的字符後面
                    while(s.charAt(left)!=s.charAt(right))
                    {
                        set.remove(s.charAt(left));
                        left++;
                    }
                    left++;
                }
                else
                {
                    set.add(s.charAt(right));
                }
                right++;
            }
            max = Math.max(max,right-left);
            return max;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章