(LeetCode)Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring"pwke" is a subsequenceand not a substring.


描述:找出字符串最長子序列,返回最長子序列長度。

解法:兩個指針i,j 作爲滑動窗口。j往後走,將不重複的字符放到HashSet裏,這樣我們就找到了以i爲起始,j爲終點的子序列。當遇到重複字符時,刪除i所在位置的字符,i向前進一位,遍歷完所有的i,即爲答案。

public int lengthOfLongestSubstring(String s) {
                    int n = s.length();
            int i =0,j=0;
            int result = 0;
            HashSet<Character> set = new HashSet<>();
            while(i<n&&j<n){
                if(!set.contains(s.charAt(j))){
                    set.add(s.charAt(j));
                    j++;
                    result = Math.max(result,j-i);//更新最長子序列長度
                }else{
                    set.remove(s.charAt(i));
                    i++;
                }
            }
        return result;
    }


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